题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
| 给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
|
解法一
思路:暴力遍历,时间复杂度为O(n^2)、空间复杂度为O(1)
| class Solution{ public int[] twoSum(int[] nums,int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[]{i, j}; } } } throw new IllegalArgumentException("no Two sum solution"); } }
|
解法二
双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。
- 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
- 如果 sum > target,移动较大的元素,使 sum 变小一些;
- 如果 sum < target,移动较小的元素,使 sum 变大一些。
数组中的元素最多遍历一次,时间复杂度为O(N)。只使用了两个额外变量,空间复杂度为O(1)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class solution{ public int[] twoSum(int[] numbers int target){ if ( numbers==null){return null;} int i = 0 ; int j = numbers.length - 1; while(i<j){ int sum = numbers[i] + numbers[j] if (sum = target){ return new int[]{i,j} }else if (sum < target){ i++; }else { j--; } } return null; } }
|
解法三
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class twoHashMap{ public int[] twoSum(int[] numbers,int target){
HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { hashMap.put(numbers[i],i); }
for (int i = 0; i < numbers.length; i++) { int complement = target - numbers[i]; if (hashMap.containsKey(complement) && hashMap.get(complement) != i){ return new int[]{i , hashMap.get(complement)}; }
} throw new IllegalArgumentException("no hava"); } }
|