[Java]1.两数之和 - LeetCode

1 题目

<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006021559422-1117932709.png"> </div>算法

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 个元素

<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006022927420-505285184.png"> </div>数组

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!");
    }
}
  • 思路三:一遍哈希表
    • 时间复杂度:O(n)
      • 只遍历了包含有n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间
    • 空间复杂度:O(n)
      • 所需的额外空间取决于哈希表中存储的元素数量,该表最多须要存储 n 个元素。
    • 原理:经过思路二,能够推得:上述过程能够一次完成。在进行迭代并将元素插入到表中的同时,咱们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。若是它存在,那咱们已经找到了对应解,并当即将其返回。
class Solution {//一次Hash查表
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap();
        for(int i=0;i<nums.length;i++){
            int tmp = target - nums[i];
            if(map.containsKey(tmp) && map.get(tmp)!=i){
                return new int [] { i, map.get(tmp) };
            } else {
                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!");
    }
}

<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006124050490-767477915.png"> </div>数据结构

3 参考文献

4 博文遗留问题

  • (数据结构/Java中)HashMap/哈希表 查询的原理与实现?
相关文章
相关标签/搜索