0
点赞
收藏
分享

微信扫一扫

leecode算法记录-2022/04/16-两数之和

东方小不点 2022-04-16 阅读 76
算法

一、题目

在这里插入图片描述

二、代码实现

1、双层循环

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

        //若数组长度为2,且相加为target,则直接返回[0,1]
        if (nums.length == 2 && (nums[0] + nums[1] == target)){
            return new int[]{0,1};
        }else if (nums.length > 2){
            for (int i = 0; i < nums.length; i++){
                for(int j = i+1; j < nums.length; j++){
                    if (nums[i] + nums[j] == target){
                        return new int[]{i,j};
                    }
                }
            }
        }
        
        return null;
    }
}

2、哈希

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

        //存哈希
        Map<Integer,Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
            int other = target - nums[i];
            if(hash.containsKey(other)){
                //如果hash中包含了此key值,返回其value值
                int j = hash.get(other);
                return new int[]{j,i};
            }else{
                //将<nums[i],i>添加至hash
                hash.put(nums[i],i);
            }
        }

        return null;
    }
}
举报

相关推荐

0 条评论