Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indice = new int[2];
        if(nums.length==0)
            return indice;
        for(int i = 0; i<nums.length;i++){
            int tmp = target - nums[i];
            for(int j = i+1; j<nums.length;j++){
                if(tmp == nums[j]){
                    indice[0]=i;
                    indice[1]=j;
                }
            }
        }
        return indice;
    }
}
采用HashMap每次添加值,key为具体值,value 为 indice。
import java.util.*;    
class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> hashTable = new HashMap<>();
            int [] indice = new int[2];
            if(nums == null)
                return indice;
            for(int i = 0; i<nums.length;i++){
                int tmp = target - nums[i];
                if(hashTable.containsKey(tmp)){
                    indice[0] = i;
                    indice[1] = hashTable.get(tmp);
                    break;
                }else{
                    hashTable.put(nums[i],i);
                }
            }
            return indice;
        }
    }

可以看到时间复杂度提高了40倍。
原文:https://www.cnblogs.com/clnsx/p/12236574.html