LeetCode 1 两数之和

LeetCode 1 两数之和

问题描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

哈希表: O(N)
使用哈希表记录下数组中值与下标的对应关系
使用哈希表快速查找数组中是否存在某个值

执行用时:3 ms, 在所有 Java 提交中击败了74.60%的用户
内存消耗:38.8 MB, 在所有 Java 提交中击败了85.02%的用户

class Solution {
    public int[] twoSum(int[] nums, int target) {
    	Map<Integer,Integer> map = new HashMap<>();
    	/*导入哈希表*/
    	for(int i=0;i<nums.length;i++) {
    		map.put(nums[i], i);
    	}
    	for(int i=0;i<nums.length;i++) {
    		int complement = target - nums[i];
    		if(map.containsKey(complement) && map.get(complement)!=i) {
    			return new int[] {i,map.get(complement)};
    		}
    	}
    	return new int[0];
    }
}
posted @ 2020-10-03 15:11  CodeSPA  阅读(70)  评论(0编辑  收藏  举报