1. The sum of two numbers
Address: https://leetcode.cn/problems/two-sum/
Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.
You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.
Example 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
Example 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
Example 3:
输入:nums = [3,3], target = 6
输出:[0,1]
hint:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Solution 1:
The way to use double pointer
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] sortNums = new int[nums.length];
for (int i=0;i<nums.length;++i) {
sortNums[i] = nums[i];
}
boolean[] used = new boolean[nums.length];
Arrays.sort(sortNums);
int i = 0;
int j = sortNums.length - 1;
while (i < j) {
int value = sortNums[i] + sortNums[j];
if (value == target) {
int oldq = find(nums, used, sortNums[i]);
int oldp = find(nums, used, sortNums[j]);
return new int[] {oldq, oldp};
}
if (value < target) {
i++;
} else {
j--;
}
}
return new int[0];
}
public int find(int[] nums, boolean[] used, int value) {
for (int i=0; i<nums.length; ++i) {
if (used[i] != true && nums[i] == value) {
used[i] = true;
return i;
}
}
return -1;
}
}
Solution 2:
Borrowing map assistance
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0;i<nums.length;i++) {
int temp = target - nums[i];
if (map.containsKey(temp)) {
return new int[] {map.get(temp), i};
} else {
map.put(nums[i], i);
}
}
return new int[] {};
}
}```
来源:力扣(LeetCode)