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

    http://www.cnblogs.com/makexu/

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号