【leetcode】Two Sum(medium)


刷100道a + b 也毫无意义。


看题目第一想法是两层遍历,明显O(n2)的时间复杂度不满足要求。

使用了java中HashMap


每次遍历数组,若这个元素在map中找不到,那么就插入,若存在,那么就找对应的target - element 的元素在不在,若存在,则返回


public static int[] twoSum(int[] nums, int target) {
        // 创建一个hashmap,将所有元素插入到hashmap中,依次遍历nums, 找存在n1+ n2 = target在表中
		HashMap <Integer,Integer> map = new HashMap<Integer,Integer>();
		int []result = new int [2];
		for ( int i = 0;i < nums.length;i++){
			Integer element = map.get(nums[i]);
			if(element == null){
				map.put(nums[i], i);
			}
			element = map.get(target - nums[i]);
			if (element != null && element < i){
				result[0] = element + 1;
				result[1] = i + 1;
				return result;
			}
		}
		return result;
    }


你可能感兴趣的:(【leetcode】Two Sum(medium))