[LeetCode]1. 两数之和

26
2020/02

# [LeetCode]1. 两数之和

## 题目

https://leetcode-cn.com/problems/two-sum/

### 示例:

给定 nums = [2, 7, 11, 15], target = 9

### 题解

hashMap：

package LeetCode;

import java.util.Arrays;
import java.util.HashMap;

public class _1_两数之和 {
public static void main(String args[]) {
int[] nums = {2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(new _1_两数之和().twoSum1(nums, target)));
}

//暴力O(n^2)
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) { // j = i + 1 的目的是减少重复计算和避免两个元素下标相
if (nums[i] + nums[j] == target) {
ans[0] = i;
ans[1] = j;
break;
}
}
}
return ans;
}

//O(n) HashMap
public int[] twoSum1(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) {
int dif = target - nums[i];//差值
if (map.get(dif) != null) {//如果差值存在
ans[0] = map.get(dif);//差值的value（索引） get
ans[1] = i;
break;
}
map.put(nums[i], i);//数字做key i坐value
}
return ans;
}
}

百度已收录

Last modification：February 26th, 2020 at 10:13 pm