前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode系列——两数之和

LeetCode系列——两数之和

作者头像
石的三次方
发布2021-01-06 09:15:58
2170
发布2021-01-06 09:15:58
举报
文章被收录于专栏:石的三次方石的三次方

两数之和

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

思路:

  • target和数组中的其中一个值做减法运算,得出一个值
  • 然后查看数组中是否存在该值,存在返回这两个数据的下标

解法:

  • 暴力破解
代码语言:javascript
复制
class Solution{
     public int[] twoSum(int[] nums, int target) 	{
        for(int i = 0 ; i < nums.length ; i++){
            int temp = target - nums[i] ;
            for(int j = i ; j <nums.length ; j++){
                if(nums[j] == temp){
                    return new int[]{i,j};
                }
            }
        }
        return null ;
     }
}
  • 哈希表查找
代码语言:javascript
复制
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hashMap = new HashMap();
        for(int i = 0 ; i < nums.length ; i++){
            int temp = target - nums[i] ;
            if(hashMap.containsKey(temp) && hashMap.get(temp) != i){
                if(i > hashMap.get(temp)) 
                    return new int[]{hashMap.get(temp),i};
                else
                    return new int[]{i,hashMap.get(temp)} ;
                
            }
            hashMap.put(nums[i],i);
        }
        return null ;
    }
}

力扣提交:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 石的三次方 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 两数之和
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档