LeetCode 1 Two Sum
2015-07-21 10:45
495 查看
1<p align="left"><span style="color: rgb(51, 51, 51);">Given an arrayof integers, find two numbers such that they add up to a specific targetnumber.</span></p><p align="left"><span style="color: rgb(51, 51, 51);">The functiontwoSum should return indices of the two numbers such that they add up to thetarget, where index1 must be less than index2. Please note that your returnedanswers (both index1 and index2) are not zero-based.</span></p><p align="left"><span style="color: rgb(51, 51, 51);">You may assumethat each input would have exactly one solution.</span></p><p align="left"><strong><span style="color: rgb(51, 51, 51);">Input:</span></strong><span style="color: rgb(51, 51, 51);"> numbers={2, 7, 11, 15}, target=9</span></p><p align="left"><strong><span style="color: rgb(54, 46, 43);">Output:</span></strong><span style="color: rgb(54, 46, 43);"> index1=1,index2=2</span></p><p><span style="color: rgb(54, 46, 43);">思路:最简单的方法就是暴力破解法,两层</span><span style="color: rgb(54, 46, 43);">for</span><span style="color: rgb(54, 46, 43);">循环,不过时间复杂度是最高的(</span><span style="color: rgb(54, 46, 43);">N</span><span style="color: rgb(54, 46, 43);">平方)。首先利用库函数</span><span style="color: rgb(54, 46, 43);">sort</span><span style="color: rgb(54, 46, 43);">进行排序,(默认的为升序),然后头尾两个变量相加,然后和</span><span style="color: rgb(54, 46, 43);">target</span><span style="color: rgb(54, 46, 43);">做比较,相等,则找到,若大于则尾变量减一,若小于则头变量加一。知道两个变量相等为止。此题还是比较简单的,因为所给的限制条件为:每一个输入都恰好有一个解。</span></p><div><span style="color: rgb(54, 46, 43);"> </span></div>
. class Solution {2. public:3. vector<int> twoSum(vector<int>& nums, int target) {4. vector<int> ivec(nums);5. std::sort(ivec.begin(),ivec.end());6. int i = 0;7. int j = ivec.size() - 1;8. int val1,val2;9. int pos1,pos2;10. while(i < j)11. {12. if((ivec[i] + ivec[j]) == target)13. {14. val1 = ivec[i];15. val2 = ivec[j];16. break;17. }18. else if((ivec[i] + ivec[j]) < target)19. ++i;20. else21. --j;22. }23.24. vector<int> ret(2,0);25. if(i == j)26. return ret;27. bool flag = true;28. for(int i = 0;i < nums.size();++i)29. {30. if(flag)31. {32. if((nums[i] == val1) || (nums[i] == val2))33. {34. pos1 = i + 1;35. flag = false;36. }37. }38. else39. {40. if((nums[i] == val1) || (nums[i] == val2))41. {42. pos2 = i + 1;43. break;44. }45. }46. }47. if(pos2 < pos1)48. {49. int tmp = pos2;50. pos2 = pos1;51. pos1 = tmp;52. }53. ret[0] = pos1;54. ret[1] = pos2;55. return ret;56.57. }58. };
相关文章推荐
- ezdpl:完全依赖脚本和ssh的自动化部署方案
- 【一天一个canvas】写文字(十四)
- GRE写作必备句型
- Apache Cordova
- 面试-JVM
- leetcode[119]:Pascal's Triangle II
- Jsp页面嵌入外部页面的方法
- 1.PhotoShop缩小图片的三种方式
- 收藏网站59
- LeetCode—Implement strStr()
- 配置SAP打印机
- 黑马程序员—— 6,多态
- 最新notepad++ 6.6.7设置tab为4个空格
- 微信支付
- Android自己动手打造XML解析框架
- 定时任务 Crontab命令 详解
- 各国语言代码
- Android模拟器的ip获取以及模拟器之间socket通信
- 403 Forbidden - WAMP Server 2.5
- Android 自定义View (四) 视频音量调控