栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1. 两数之和 - - LeetCode [ java ]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1. 两数之和 - - LeetCode [ java ]

题目

思路
思路时间复杂度描述
通常冒泡排序原型O(n²)
进阶hashmapO(n)理论

Step1. 循环时,将 key= target-num[i] ,value = i 存入hashmap

Step2. 下一次循环时 若num[i+1] = value 则返回对应的下标

答案
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++) {
                if (target == nums[i] + nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}
总结

        1. leetcode 提交代码时 不需要import  jdk包含的包。

        2. 复习时间复杂度。这里的时间复杂度依然是 O(n²),若能找到更小的时间复杂度希望读者能够留言

        3. 进阶 - 复习haspMap时间复杂度(不发生碰撞时,hashmap所有方法时间复杂度为O(1))

进阶
// 这里haspmap不发生碰撞的话,该方法时间复杂度为O(n)
// 思路
//  Step 1 循环遍历 nums
//  Step 2 每次循环计算流程
//  Step 2-1 判断 hash  Map 中是否有nums[i] 有保存结果indexs ,return indexs
//  Step 2-2 put(target-nums[i],i) 到 hash  Map中
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indexs = new int[2];
        
        // 建立k-v ,一一对应的哈希表
        HashMap hash = new HashMap();
        for(int i = 0; i < nums.length; i++){
            if(hash.containsKey(nums[i])){
                indexs[0] = hash.get(nums[i]);
                indexs[1] = i;
                return indexs;
            }
            hash.put(target-nums[i],i);
        }
        return indexs;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/591084.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号