题目

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

示例

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

个人解法

思路:纯暴力解。两个for循环,枚举数组中所有两数相加的情况,并与target判断

class Solution {
    public static int[] twoSum(int[] nums, int target) {
        //声明一个存放结果的数组
        int [] result = new int[2];
        //遍历
        for(int i = 0; i < nums.length - 1 ; i++){
            for(int j = i+1; j < nums.length ; j++){
                if(nums[i]+nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        //若找不到
        result[0] = -1;
        result[1] = -1;
        return result;
    }
}

官方解法

需要学习的点:Map的特性与方法

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        //实例化map对象:像键值对一样存储 , 如{2:0, 7:1, 11:2, 15:3}
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        //遍历数组,将数组元素作为键,数组下标作为值存入map中
        for (int i = 0; i < nums.length; ++i) {
            //若map中存在target-nums[i]的键,则找到了两个元素的和为target,返回这两个元素的下标
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
                hashtable.put(nums[i], i);
            }
            return new int[0];
    }
}