Leetcode - Hash table - Easy (1,202)

虽然题目是从Hash Table tag里搜出来的,但用HashMap/HashSet只是解法之一,有些题目的奇技淫巧还需看其他解法,我尽量整理在一起。

  1. Two Sum
    Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    You can return the answer in any order.
    Example 1:
    Input: nums = [2,7,11,15], target = 9
    Output: [0,1] Because nums[0] + nums[1] == 9, we return [0, 1].
    hashmap基本上可以等同于hashtable。而且可以看作为其升级版。HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键值(key)和值(value),而Hashtable则不行)。
/**
 * hash map中存遍历的数组元素和它的index,遍历的过程中比较有没有符合条件的值,碰到则返回
 */
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hm = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(hm.get(target-nums[i])!=null){
                return new int[]{i,hm.get(target-nums[i])};
            }
            hm.put(nums[i],i);
        }
        return new int[]{1,1,1};
    }
}
  1. Single Number
    Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
    Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
/**
 * 用hash map的常规思路O(n) 9 ms 39.3 MB
 */
class Solution1 {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums){ 
            map.put(num,map.getOrDefault(num,0)+1);
        }
        for(int num : nums){
           if(map.get(num)==1){
               return num;
           }
        }
        return -1;
    }
}
/**
 * 数学解法2∗(a+b+c)−(a+a+b+b+c)=c  复杂度6 ms,39.1 MB
 */
class Solution2 {
    public int singleNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int setSum=0, numSum=0;
        for(int num:nums){
            if(!set.contains(num)){
                set.add(num);
                setSum+=num;
            }
            numSum+=num;
        }
        return 2*setSum-numSum;
    } 
}

Bit Manipulation

a b a ^ b
0 0 0
0 1 1
1 0 1
1 1 0

a⊕0=a
a⊕a=0
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b

/**
 * 神奇解法 1 ms	38.9 MB
 */
class Solution3 {
    public int singleNumber(int[] nums) {
        int a=0;
        for (int num : nums){ 
           a^=num;
        }
        return a;
    }
}
  1. Happy number
    Write an algorithm to determine if a number n is happy.
    A happy number is a number defined by the following process:
    1.Starting with any positive integer, replace the number by the sum of the squares of its digits.
    2.Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
    3.Those numbers for which this process ends in 1 are happy.
    4.Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
/**
 * 举例得知非快乐数最后会进入重复循环,所以用set记录有过的sum of the squares of its digits。如果有重复sum出现说明不是快乐数,如果结果为1,判断是快乐数
 * 1 ms	36.4 MB
 */
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while(true){
            int sum = squareSum(n);
            if(sum==1){
                return true;
            }
            if(set.contains(sum)){
                return false;
            }else{
                set.add(sum);
            }
            n=sum;
        }
    }
    private int squareSum(int n){
        int sum = 0;
        while(n>0){
            int d=n % 10;
            sum += d*d;
            n /= 10;
        }
        return sum;
    }
}
/**
 * 快慢指针的神奇算法,当不快乐数字进入死循环后,两指针总要碰面
 * 0 ms	35.7 MB
 */
class Solution {
    public boolean isHappy(int n) {
        if(n==1||n==-1){return true;}
        int slow=n, fast=n;
        while(true){
            slow=squareSum(slow);
            fast=squareSum(fast);
            fast=squareSum(fast);
            if(fast==1){return true;}
            else if(fast==slow){return false;}
        }
    }
    private int squareSum(int n){
        int sum = 0;
        while(n>0){
            int d=n % 10;
            sum += d*d;
            n /= 10;
        }
        return sum;
    }

你可能感兴趣的:(Leetcode - Hash table - Easy (1,202))