leetcode-hot100 每日一题(两数之和)

73 阅读1分钟

image.png

方法1:双层循环遍历

image.png

//双层循环

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
            //从当前数的后一个数开始往后找,找到与当前数相加等于target的数
                if(nums[i]+nums[j]==target)
                //找到数组返回两个数的下标
                return new int[] {i,j} ;

            }
        }
        //不存在返回空数组
        return new int[0];
        
    }
}

方法2:哈希表

hashmap.get(Object key):获得key对应的value
hashMap.put(key,value):添加到map中
hashmap.containkey(key):map中是否存在key

image.png

//哈希表
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        HashMap<Integer,Integer> numMap=new HashMap<>();
        for(int i=0;i<nums.length;i++){
        //查找hashmap中能与当前数相加等于target的key,并返回他的value(key为数组值,value为数组值对应的索引)
            Integer left = numMap.get(target - nums[i]);
            //存在则保存数组返回
            if(left!=null){
                res[0]=left;
                res[1]=i;
                break;
            }else {
            //不存在,则将当前数组保存至hashmap
                numMap.put(nums[i],i);
            }
        }
        return res;
    }
}