首页 > 其他分享 >leetcode1-两数之和

leetcode1-两数之和

时间:2022-08-14 19:01:08浏览次数:92  
标签:map return target nums int leetcode1 两数

两数之和

  • 暴力遍历
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for(int i = 0; i < n; i++){
            for(int j = i+1; j < n; j++){
                if(nums[i]+nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}
  • 哈希
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return null;
    }
}

标签:map,return,target,nums,int,leetcode1,两数
From: https://www.cnblogs.com/xzh-yyds/p/16586044.html

相关文章

  • leetcode2-两数相加
    两数相加循环,每次相加都new一个新的节点classSolution{publicListNodeaddTwoNumbers(ListNodel1,ListNodel2){ListNodehead=null,tail=nu......