LeetCode----Two Sum
2015-03-09 21:52
253 查看
Two Sum
Total Accepted: 69182 TotalSubmissions: 382018My Submissions
Question
Solution
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
这道题网上有很多解法,好多都是使用map或者hash来解的,效率相对也比较高。但本题不能用两个循环来解决,
因为会超时,因此我们需要对算法进行优化。
我的思路如下,先用一个临时数组(temp)存储原数组的数据,然后对其进行排序,再设置两个指针left和
right,分别指向排序后数组的头和尾,利用二分查找的思想,如果temp[left] + temp[right] == target,已找到(唯一),
退出循环。否则,如果temp[left] + temp[right] > target,将right-1,否则left+1,基于这种二分的思想,最终会找到
满足条件的两个数,他们分别是temp[left]和temp[right],下面只要在原数组numbers中在找到这两个数的下标即可,
注意下标要从1开始,同时要注意有相等数字的出现,处理的办法是一个从前往后查找,一个从后往前查找,最后要
注意下两个下标需从小到大。代码如下:
int cmp(const void *a,const void *b) { return *(int *)a - *(int *)b; } int *twoSum(int numbers[], int n, int target) { int * ans = (int *)malloc(sizeof(int)*2); int temp ; int i; for(i = 0;i<n;++i) temp[i] = numbers[i]; qsort(temp,n,sizeof(int),cmp); int left = 0; int right = n-1; while(left < right) { if(temp[left] + temp[right] == target) break; else if(temp[left] + temp[right] > target) right--; else left++; } for(i = 0;i<n;++i) { if(numbers[i] == temp[left]) { ans[0] = i+1; break; } } for(i = n-1;i>=0;--i) { if(numbers[i] == temp[right]) { ans[1] = i+1; break; } } if(ans[0] > ans[1]) { int t = ans[0]; ans[0] = ans[1]; ans[1] = t; } return ans; }
相关文章推荐
- LeetCode1-Two Sum
- 1---LeetCode【Two Sum】|C语言|总结
- [LeetCode] Two Sum
- LeetCode【1】Two Sum
- LeetCode-1 Two Sum
- Java 哈希表运用-LeetCode 1 Two Sum
- 【LeetCode 1】算法修炼 --- Two Sum
- LeetCode - Two Sum
- leetcode 1 Two Sum
- leetcode 小试-- Two Sum
- leetcode---------------Two Sum
- [leetcode, python] Two Sum 两数之和等于某数
- LeetCode第一题Two Sum
- leetcode:Two Sum
- leetcode_two sum
- [C++]LeetCode: 14 Two Sum
- [leetcode]Two Sum
- leetcode 1. Two Sum [Easy]
- LeetCode:Two Sum
- [LeetCode] Two sum