Leetcode第一题:两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1 暴力for循环

class Solution {
    public static int[] twoSum(int[] nums, int target) {

		for (int i = 0; i < nums.length-1; i++) { // 第一层循环
			for (int j = i + 1; j < nums.length; j++) { // 下一个数循环
				if (nums[i] + nums[j] == target) { // 找到就返回
					int[] indexes = new int[2];
					indexes[0] = i;
					indexes[1] = j;
					return indexes;
				}
			}
		}
		return null;
	}
}

2 引入Hash表

  1. 通过加入 hash 表以空间换取时间减少查找时间,若出现哈希冲突,查找效率会出现一定程度的退化。

  2. 遍历数组中数插入哈希表的同时,检查表中是否存在和当前数和为 target 的已有数。

    class Solution {
     	public static int[] twoSum(int[] nums, int target) {
    
    		Map<Integer, Integer> resultMap = new HashMap<>();
    
    		for (int i = 0; i < nums.length; i++) {
    			int value = target - nums[i];
    			if (resultMap.containsKey(value)) {
    				if (i>resultMap.get(value)){
    					return new int[]{resultMap.get(value), i};
    				}
    			}
    			resultMap.put(nums[i], i);
    		}
    		return null;
    	}
    }
    
posted @ 2020-04-26 22:11  teago  阅读(104)  评论(0)    收藏  举报