01_TwoNums

1.问题

2.Solution

public static int[] solution(int[] array,int target){
    int len = array.length;
    for(int i = 0; i < len - 1; i++){
        for(int j = i + 1; j < len ; j++){
            if(array[i] + array[j] == target){
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

 

使用map将复杂度从O(n2)降至O(n),

map的键存的是数值

map的值存的是位置

在for循环中查找数据使用map可以大大的降低复杂度

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

 

3.Test

posted @ 2016-06-19 10:39  桃源仙居  阅读(156)  评论(0)    收藏  举报