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

aba ^ b
000
011
101
110

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值