Fetching contributors…
Cannot retrieve contributors at this time
98 lines (67 sloc) 2.15 KB
title date categories tags
LeetCode1-两数之和
2019-06-01

LeetCode

## 分析

### 优化解

1. map中的存储为 (数组元素，当前角标)
2. 首先遍历到2，9-2=7。判断7是否在map中。若不在，就将 (2,0)装入map。
3. 然后到7了，9-7=2,。发现在map中，完美解决

## 解答

```import org.junit.Test;
public class LeetCode1Test {

@Test
public void test(){
int[] nums = {2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(twoSumBao(nums,target)));
System.out.println(Arrays.toString(twoSumYou(nums,target)));
}

public int[] twoSumBao(int[] nums, int target) {
if(nums == null || nums.length < 2){
return new int[]{-1,-1};
}
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[]{-1,-1};
}

public int[] twoSumYou(int[] nums, int target) {
if(nums == null || nums.length < 2){
return new int[]{-1,-1};
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
int otherValue = target - nums[i];
if(map.containsKey(otherValue)){
return new int[]{map.get(otherValue),i};
}else{
map.put(nums[i],i);
}
}
return new int[]{-1,-1};
}
}

```
You can’t perform that action at this time.