码迷,mamicode.com
首页 > 编程语言 > 详细

[Java]1.两数之和 - LeetCode

时间:2019-10-06 09:24:12      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:inf   数组   turn   public   ash   target   sum   solution   遍历   

1 题目

技术图片

2 思路与代码

  • 思路一:暴力法(两层For循环)
    • 时间复杂度:O(n^2)
      • 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。因此时间复杂度为 O(n^2)。
    • 空间复杂度:O(1)
    • 原理:遍历每个元素 xx,并查找是否存在一个值与 target - x相等的目标元素
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target){
    static int result[2]= {0};
    for(int i=0;i<numsSize;i=i++){
        for(int j=i+1;j<numsSize;j=j++){ //【trick】“int j=i+1;”而非“int j=0”
            if(nums[i]+nums[j]==target){
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    return result;
}
  • 思路二:两遍哈希表
    • 时间复杂度:O(n)
      • 把包含有 n 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1) ,所以时间复杂度为O(n)
    • 空间复杂度:O(n)
      • 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n 个元素
技术图片
class Solution {
    /*
     思路:两遍哈希表
     推荐文献:
        https://baijiahao.baidu.com/s?id=1628609734622761569&wfr=spider&for=pc
    */
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for(int j=0;j<nums.length;j++){
            int tmp = target - nums[j];
            if(map.containsKey(tmp) && map.get(tmp)!=j){
                return new int [] { j, map.get(tmp) };
            }
        }
        throw new IllegalArgumentException("No two sum solution!");
    }
}
  • 思路三:一遍哈希表

3 参考文献

4 博文遗留问题

  • (数据结构/Java中)HashMap/哈希表 查询的原理与实现?
  • 三大思路的全部复现与详细阐述

[Java]1.两数之和 - LeetCode

标签:inf   数组   turn   public   ash   target   sum   solution   遍历   

原文地址:https://www.cnblogs.com/johnnyzen/p/11626301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!