最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

哈希表系列一>两数之和

网站源码admin4浏览0评论

哈希表系列一>两数之和

题目:

链接: link

方法:

暴力代码:

代码语言:javascript代码运行次数:0运行复制
public int[] twoSum(int[] nums, int target) {
        解法一:暴力解法:
        int n = nums.length;
        for(int i = 1; i <= n; i++)
            for(int j = i-1; j >= 0; j--){
                if(target == nums[i] + nums[j]){
                    return new int[]{i,j};
                }
            }

        return null;    
 }

优化后代码:

代码语言:javascript代码运行次数:0运行复制
class Solution {
        //解法二:用哈希表优化:
        Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>
        
        for(int i = 0; i < nums.length; i++){
            int find = target - nums[i];
            if(hash.containsKey(find)){
                return new int[]{i,hash.get(find)};
            }
            hash.put(nums[i],i);
        }

        return null;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-03,如有侵权请联系 cloudcommunity@tencent 删除returntarget优化hashint

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论