题目见:https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这道题简单讲就是要在一串数字中,找到两个数相加等于给定的数,并返回这两个数的位置。
我的想法是:
- 将这串数字从小到大排序
- 将第一个数和最后一个数相加,然后和给定的数进行判断
- 如果等于给定的数,那就直接返回
- 如果小于给定的数,就取比小的数稍大的数,也就是第二位,来和最后一位相加
- 如果大于给定的数,就取比大的数稍小的数,也就是倒数第二位,来和第一位相加
- 以此类推,只要不等于给定的数,往复循环第二步,直到相等为止。
时间与空间使用信息
Runtime: 1 ms, faster than 99.91% of Java online submissions for Two Sum.
Memory Usage: 39.8 MB, less than 5.65% of Java online submissions for Two Sum.
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
int start = 0;
int end = length - 1;
int startNum = 0, endNum = 0;
int posOne = 0,posTwo = 0;
int[] sortedNums = nums.clone();
Arrays.sort(sortedNums); //将这串数字从小到大排序
for (int i = 0; i < length; i++) { //将第一个数和最后一个数相加,然后和给定的数进行判断
if ((sortedNums[start] + sortedNums[end]) < target) {
//如果小于给定的数,就取比小的数稍大的数,来和最后一位相加
start++;
} else if ((sortedNums[start] + sortedNums[end]) > target) {
//如果大于给定的数,就取比大的数稍小的数,来和第一位相加
end--;
} else {
//如果等于给定的数,那就直接返回
startNum = sortedNums[start];
endNum = sortedNums[end];
break;
}
}
boolean flagOne = false, flagTwo = false;
for(int i = 0; i < length; i++) {
if(nums[i] == startNum && !flagOne) {
posOne = i;
flagOne = true;
} else if(nums[i] == endNum && !flagTwo) {
posTwo = i;
flagTwo = true;
}
if(flagOne && flagTwo) {
break;
}
}
return new int[]{posOne, posTwo};
}