問題:LeetCode1:TwoSum
Given an array of integers, find two numbers such that they addup to a specific target number.
The function twoSum should return indices of the two numberssuch 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 notzero-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
算法思想:
用一般的方法算法的複雜度較高,我想到一個簡單的思路:
首先,對給出的數組升序排序(降序也可以,整體倒過來也行)。時間複雜度最快爲lgN。然後,折半找數組中的數據,記住最後一個比給出的和小的那個位置b(實際上應該是target減去數組的第一個數,詳細解釋在代碼中)。從這個位置開始向前找,利用快速排序的思想從0到b之間找兩個數,使之和等於target。
這個方法實現的程序(C#實現)通過了LeetCode檢測,提示用了16個測試,用時492ms,超過了75%的人。
希望誰還有更好的方法拿出啦分享,大家一起進步。
下載地址:http://download.csdn.net/detail/worsun/9119589
不想下載的下面也有一樣的代碼。
代碼:
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] temp = (int [])nums.Clone();//保存原順序 注意:這裏要求深拷貝,不能是淺拷貝,直接賦值是淺拷貝
int[] tempResult = new int[] { 0, 0};
int[] result = new int[] { 0,0};
Array.Sort(nums);
int pre = 0;
////之所以用target-nums[0]是因爲有可能nums[0]爲負數,兩個數相加更小了,造成不準確。所以要減去nums[0]
int rear = FindLocation(nums, 0, nums.Length, target – nums[0]);
//if(nums[rear] == target && nums[0] == 0)//如果找到rear恰好等於target,由於數組有序,所以只要找數組的第一個數是不是等於0即可
//{
// result[0] = 1;
// result[1] = rear + 1;
// return result;
//}
while(pre < rear)//採用快速排序的想法,從兩邊進行
{
while(nums[pre] + nums[rear] < target)
{
if(pre == rear)//如果兩個數相等後,nums[pre] + nums[rear] < target還成立的話,那麼不存在符合條件的情況,跳出循環
{
return tempResult;
}
pre++;
}
if(nums[pre] + nums[rear] == target)
{
tempResult[0] = pre;
tempResult[1] = rear;
break;
}
rear–;
}
for(int i = 0, j = 0; i < temp.Length; i++ )
{
if(nums[tempResult[0]] == temp[i] || nums[tempResult[1]] == temp[i])
{
result[j++] = i + 1;
}
}
Array.Sort(result);
return result;
}
public static int FindLocation(int[] nums, int low, int hight, int target)
{//-3,3,4,90
if(1 == hight – low)
{
return low;
}
int location = (low + hight) / 2;
if(target < nums[location])
{
return FindLocation(nums, low, location, target);
}
else if(target == nums[location])
{
return location;
}
else
{
return FindLocation(nums, location, hight, target);
}
}
}
下載地址:http://download.csdn.net/detail/worsun/9119589