LeetCode 1 Two Sum 排序后快速求解
2016-06-08 00:00
381 查看
Two Sum
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 开始我利用c语言实现了这个算法,但是LeetCode服务器抽风,不能通过我的c版本的代码,无奈之下,利用Java重构了该代码。算法思路很简单,首先利用快速排序改造序列,并且在另一个数组里面记录改变的序号。在这个基础之上,利用首尾相加,若大于target,尾部左移。若小于target,头部前移。 代码如下: public int[] twoSum(int[] nums, int target){
int size = nums.length;
int index[] = new int[size];
for (int i = 0; i < nums.length; i++) {
index[i]=i+1;
}
quickSort(nums,index, 0, nums.length-1);
int left = 0;
int right = nums.length-1;
while (left!=right)
{
if (nums[left]+nums[right] == target)
{
int [] ai = new int[]{0, 0};
ai[0] = index[left];
ai[1] = index[right];
if (ai[0]>ai[1])
{
int temp = ai[0];
ai[0] = ai[1];
ai[1] = temp;
}
return ai;
}
else if (nums[left] + nums[right] > target)
{
right--;
}
else{
left++;
}
}
return null;
}
public void quickSort(int anData[], int index[],int nLeft, int nRight)
{
int nPivot = anData[nLeft + (nRight - nLeft) / 2];
int i = nLeft;
int j = nRight;
while (i <= j)
{
while (anData[i] < nPivot) ++i;
while (anData[j] > nPivot) --j;
if (i <= j)
{
int nTemp = anData[i];
anData[i] = anData[j];
anData[j] = nTemp;
int iTemp = index[i];
index[i] = index[j];
index[j] = iTemp;
++i;
--j;
}
}
if (nLeft < j) quickSort(anData,index, nLeft, j);
if (nRight > i) quickSort(anData,index, i, nRight);
}
在上述基础上,利用map有着更高的效率,原理基本一致,map(target - number[i])。该语句使得整个复杂度达到O(n),利用该语句可以快速求出结果。
map对应key为值,map索引结果为number数组的初始索引。
代码如下:
public int[] twoSum(int[] numbers, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int n = numbers.length;
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++)
{
if (map.containsKey(target - numbers[i]))
{
result[0] = map.get(target-numbers[i]) + 1;
result[1] = i + 1;
break;
}
else
{
map.put(numbers[i], i);
}
}
return result;
}
相关文章推荐
- C++Primer Plus 基础复习
- LeetCode 22 Generate Parentheses 卡特兰数问题,有待进一步学习
- LeetCode 3 Longest Substring Without Repeating Characters
- NULL 是什么 && 为什么要使用 strlen(s) + 1
- LeetCode Remove Duplicates 个人解法以及一些高效解法
- LeetCode 5 Longest Palindromic Substring
- LeetCode 42 Trapping Rain Water
- windows下python 安装igraph库报错 Cannot find the C core of igraph on this system using pkg-config.的解决
- 顶层const 与底层const
- 使用Rxjava的compose()操作符
- linux线程函数
- LeetCode 43 Multiply Strings
- 产品制作流程
- LeetCode 4 Median of Two Sorted Arrays
- 研一上学习任务
- union 和 struct 的区别与联系
- linux 源内核加载模块
- 未来规划 2016 1 - 6月
- LeetCode 25 Reverse Nodes in k-Group
- LeetCode 30 Substring with Concatenation of All Words 解法为Hashmap