多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > 綜合技術 > LeetCode Two Sum

LeetCode Two Sum

來源:程序員人生   發布時間:2015-03-31 08:15:40 閱讀次數:3297次

1.題目


Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


2.解決方案之1

typedef struct node{ int originalIndex; int val; node(){}; node(int index, int v):originalIndex(index),val(v){} } Node; bool compare(const Node& a, const Node& b){ return a.val < b.val; } class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; int length = numbers.size(); vector<Node> nums(length); for(int i = 0; i < numbers.size(); ++i){ nums[i] = Node(i, numbers[i]); } sort(nums.begin(), nums.end(), compare); int left = 0; int right = length - 1; while(left < right){ int sum = nums[left].val + nums[right].val; if(sum == target){ result.push_back(min(nums[left].originalIndex + 1, nums[right].originalIndex + 1)); result.push_back(max(nums[left].originalIndex + 1, nums[right].originalIndex + 1)); break; }else if(sum < target){ left++; }else{ right--; } } return result; } };


思路:先排序,然后頭尾相加進行判斷,如果太小了,把左側的標記index往右移動1個,如果太大了,把右側的標記index往左移動,直到找到為止。


http://www.waitingfy.com/archives/1577

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 国产日本韩国不卡在线视频 | 欧美天天性 | 午夜在线亚洲 | 亚洲欧美一区二区三区 | 成人欧美日韩高清不卡 | 操操色| 国产1区2区3区 | 成人 在线欧美亚洲 | 国产高清一级毛片在线不卡 | www.亚洲精品 | 国产xxx护士爽免费看 | 日本高清www午色夜黄 | 亚洲狠狠狠一区二区三区 | 免费一级毛片一级毛片aa | 性欧美tubepornofree| 性欧美xxxxhd | 亚洲好视频 | 欧美另类网 | www.精品国产 | 欧美视频一区二区在线观看 | 天堂福利视频在线观看 | 老司机午夜在线 | 网站四虎1515hhcom | 亚洲综合一区二区 | 成人自拍视频 | 欧美国产亚洲精品a第一页 欧美国产亚洲精品高清不卡 | 最近中文字幕2019免费版日本 | 最近手机中文字幕高清1 | 亚洲图片校园另激情类小说 | 91桃色观看免费高清 | 一区二区三区在线 | 网站 | 午夜写真福利视频在线观看 | 淫欲影院 | www.黄网站| 666精品国产精品亚洲 | 日本怡春院欧美一区二区三区 | 国内免费视频成人精品 | japanese护士| 最新中文字幕av专区 | 欧美 日韩 亚洲另类专区 | 日韩理论片在线观看 |