LeetCode - Two Sum

23.07.2021

小白一枚,文章仅当日记本记录学习进度 ;)

如被浏览,请多多指教,非常感谢大家纠错与建议!

(因留学顺便练习英语,所以用英文笔记,并无他意)

1. Two Sum 

Solution 0 - 2 for loops (Java) 

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

Solution 1 - for loop (Python)

def twoSum(nums, target):
    j = 0
    for i in nums:
        j += 1
        if target - i in nums[j:]:
            return [j-1, nums[j:].index(target - i) + j]

Note:

1. "return indices of the two numbers" - not elements

2. "you may not use the same element twice" - return [nums.index(i), nums.index(target - i)] seems reasonable but it will always return two same indices if there are two same elements in the list.

3. This is one of  algorithms that is less than O(n2) time complexity

Solution 2 - Two-pass Hash Table ( Python & Java)

Python: https://medium.com/@havbgbg68/leetcode-1-two-sum-python-8d77c223abd3

def twoSum(nums, target):
    hashTable = {}
    for i in range(len(nums)):
        hashTable[nums[i]] = i
    for i in range(len(nums)):
        if target - nums[i] in hashTable:
            # check if it is the same element(avoid self + self = target)
            if hashTable[target - nums[i]] != i:
                return [i, hashTable[target - nums[i]]]
    return []
  

Java: https://www.bilibili.com/video/BV1Ka411F7au?from=search&seid=11907029838860638350

class Solution {

    /** My solution */

    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i]) && 
                map.get(target - nums[i]) != i) {
                res[0] = i;
                res[1] = map.get(target - nums[i]);
                return res;
            }
        }
        return null;
    }     
}

Solution 3 - One-pass Hash table (Python) 

https://medium.com/@havbgbg68/leetcode-1-two-sum-python-8d77c223abd3

def twoSum(self, nums, target):
    hash_table = {}
    for i, num in enumerate(nums):
        if target - num in hash_table:
            return [hash_table[target - num], i]
            hash_table[num] = i
    return []
     

Hash table :

https://www.youtube.com/watch?v=sfWyugl4JWA

To build a hash table , first you need an array, we should put each key value pair into this array

Solutions for Collision ( when multiple keys try to get to the same spot)

1. Chaining

Instead of directly storing the key value pairs in the array, we store then in the link list, we have a pointer to that linked list 

2. Open addressing

Linear probing : check the element which is directly to the right of the collision, if it's empty then put it there, keep checking the element to the right until we can find an empty position. Double-hashing : pick a number which determine how many elements we wanna check ahead, if the position doesn't exist, then go back to the firs element.

Summary:

1. We first pick our initial index for the given key with hash funciton h1 with the mod of the array's length. i = h1(key) mod length

2. ( i + c ) mod length, ( i + 2c ) mod length, gcd(c, m) =1; c <- {h2(key) mod (m-1)} + 1

h2(key) = h1(key + 'd'), h2(key) = h1(key) ; pick m to be a prime number

Python dict VS Java HashMap

https://zhuanlan.zhihu.com/p/33496977

Java IDE Tips

itar + tab -----> for (int i = 0; i < array.length; i++) { }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值