您的位置:首页 > 其它

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;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: