LeetCode热题 首题 两数之和

简介: LeetCode热题 首题 两数之和

暴力破解法,运用数组两数之和相加,直到两数之和相加成目标值为止。但时间复杂度为O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        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){
                    result[0]=i;
                    result[1]=j;
                    break;
                }
            }
        }
        return result;
    }
}

哈希表方法:通过利用哈希表存储,我们通过哈希表,查找表中是否有target-nums[i]这个数据,

若没有,哈希表插入x,并伴随记录数组位置。、

哈希表方法将时间复杂度降低到从 O(N) 降低到 O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> ht=new HashMap<Integer,Integer>();
        for(int i = 0;i < nums.length;i++){
            if(ht.containsKey(target-nums[i])){
                return new int[]{ht.get(target-nums[i]),i};
            }
            ht.put(nums[i],i);
        }
        return new int[0];
    }
}


相关文章
LeetCode 热题100——单调栈
LeetCode 热题100——单调栈
19 0
|
1月前
|
算法
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
LeetCode刷题---167. 两数之和 II - 输入有序数组(双指针-对撞指针)
|
3月前
|
索引 容器
双指针解决leetcode1两数之和
双指针解决leetcode1两数之和
19 0
|
1月前
|
存储 算法
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
|
1月前
|
网络协议
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
|
1月前
《LeetCode 热题 HOT 100》—— 两数相加
《LeetCode 热题 HOT 100》—— 两数相加
|
1月前
leetcode热题100. 字母异位词分组
leetcode热题100. 字母异位词分组
16 0
|
1月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
1月前
|
算法
leetcode热题100.三数之和
leetcode热题100.三数之和
17 1
|
1月前
leetcode热题100. 二叉树的最近公共祖先
leetcode热题100. 二叉树的最近公共祖先
20 0