LeetCode Two Sum
2016-11-21 20:57
429 查看
Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
1、快速排序
由于所给了array不是有序的,所以循环相加,时间会是O(m2), 这显然符合要求,所以可以先对array进行排序,快速排序的时间复杂度是 O(mlog(m)),明显复杂度要降低不少。但是题目要求得到的是原array的下标,所以在进行快速排序的时候需要同时对下标进行移位。这只需要在在快排函数中加入一个下标array,并且随元素进行移位排序代码 :
void quick_sort(vector<int>&s, int l, int h,vector<int>&index) { if (l < h) { int i = l, j 4000 = h, x = s[l],key=index[l]; while (i < j) { while(i < j && s[j] >= x) j--; if(i < j) { index[i]=index[j]; s[i++] = s[j]; } while(i < j && s[i] < x) i++; if(i < j) { index[j]=index[i]; s[j--] = s[i]; } } s[i] = x; index[i]=key; quick_sort(s, l, i - 1,index); // 递归调用 quick_sort(s, i + 1, h,index); } }
2、寻找符合条件的下标
在排序后,对有序array从左右两边进行循环判断是否符合,时间复杂度是O(m),一直把所有可能的组合进行遍历输出结果代码如下:
while(i < j){ int x = nums[i] + nums[j]; if(x == target){ r.push_back(index[i]); r.push_back(index[j]); i++; j--; }else if(x > target) j--; else i++; }
相关文章推荐
- LeetCode题目解析(一):1、two sum
- leetCode 1. Two Sum
- [LeetCode]Two Sum
- leetcode--1. Two Sum
- LeetCode之Two Sum
- [LeetCode] Two Sum, Solution
- leetcode刷题笔记-two sum
- LeetCode --- 1. Two Sum
- 【LeetCode】1. Two Sum
- LeetCode习题笔记——Two Sum
- Two Sum[leetcode]
- 【Leetcode】001 Two Sum
- leetcode - 1. Two Sum (java)
- LeetCode|Two Sum-java
- [leetcode, python] Two Sum 两数之和等于某数
- Two Sum -- LeetCode [数组类]
- [编程练习][Two Sum]<LeetCode-1>
- LeetCode——01 Two Sum
- LeetCode1:Two Sum
- [LeetCode]--1. Two Sum