Leetcode-1 两数之和

Leetcode-1 两数之和_第1张图片

暴力穷举

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] num = 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){
                    num[0]=i;
                    num[1]=j;
                }
            }
        }
        return num;
    }
}

HashMap,记录下标和对应值,避免二次扫描
key为元素值,value为每个元素对应下标

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> storeMap = new HashMap<>(nums.length+1);
        int[] res = new int[2];
        for(int i=0;i<nums.length;i++){
            int another = target-nums[i];
            Integer anotherIndex=storeMap.get(another);
            if(null!=anotherIndex){
                res[0]=anotherIndex;
                res[1]=i;
                break;
            }else{
                storeMap.put(nums[i],i);
            }
        }
        return res;
    }
}

你可能感兴趣的:(Leetcode刷题,leetcode,算法,数据结构)