Hash Table-------(easy四道题)(medium五道题)

easy

1. Two Sum

Given an array of integers, return indices of the two numbers such
that they add up to a specific target.Given an array of integers,
return indices of the two numbers such that they add up to a specific
target.

You may assume that each input would have exactly one solution, and
you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

Accepted Java O(n) Solution:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
        return result;
        
    }
}

136. Single Number

Given a non-empty array of integers, every element appears twice
except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?

Example 1:

Input: [2,2,1] Output: 1

Example 2:

Input: [4,1,2,1,2] Output: 4

My O(n) solution using XOR:

class Solution {
    int singleNumber(int A[], int n) {
        int result = 0;
        for (int i = 0; i<n; i++)
        {
            result ^=A[i];
        }
        return result;
    }
}

Easiest way to solve by using bit manipulation:

Logic: XOR will return 1 only on two different bits. So if two numbers
are the same, XOR will return 0. Finally only one number left. A ^ A =
0 and A ^ B ^ A = B.

class Solution {
    public:
        int singleNumber(int A[], int n) {
            int result=A[0];
            for(int i=1;i<n;i++)
            {
                result= result^A[i];  /* Get the xor of all elements */
            }
            return result;
        }
    };

438. Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices
of p’s anagrams in s.

Strings consists of lowercase English letters only and the length of
both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input: s: “cbaebabacd” p: “abc”

Output: [0, 6]

Explanation: The substring with start index = 0 is “cba”, which is an
anagram of “abc”. The substring with start index = 6 is “bac”, which
is an anagram of “abc”.

Example 2:

Input: s: “abab” p: “ab”

Output: [0, 1, 2]

Explanation: The substring with start index = 0 is “ab”, which is an
anagram of “ab”. The substring with start index = 1 is “ba”, which is
an anagram of “ab”. The substring with start index = 2 is “ab”, which
is an anagram of “ab”.

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92015/ShortestConcise-JAVA-O(n)-Sliding-Window-Solution

771. Jewels and Stones

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

Example 1:

Input: J = “aA”, S = “aAAbbbb” Output: 3

Example 2:

Input: J = “z”, S = “ZZ” Output: 0

Note:

S and J will consist of letters and have length at most 50. The characters in J are distinct.

正则:

class Solution {
    public int numJewelsInStones(String J, String S) {
        return S.replaceAll("[^" + J + "]", "").length();
    }
}

Set Solution O(M+N):

class Solution {
    public int numJewelsInStones(String J, String S) {
            int res = 0;
            Set setJ = new HashSet();
            for (char j: J.toCharArray()) setJ.add(j);
            for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
            return res;
    }
}

Explanation

read J and build jewels hash set. read S and count jewels. Time complexity I used hash set and it’s O(1) to check if it contains an element. So the total time complexity will be O(M+N), instead of O(MN)

medium

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
在这里插入图片描述

11-line simple Java solution, O(n) with explanation:

the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.

class Solution {
   public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
}

49. Group Anagrams

Given an array of strings, group anagrams together.
在这里插入图片描述
Note:
All inputs will be in lowercase.
The order of your output does not matter.

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String keyStr = String.valueOf(ca);
            if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
            map.get(keyStr).add(s);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.
在这里插入图片描述
Follow up: Recursive solution is trivial, could you do it iteratively?

Iterative solution in Java - simple and readable:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;

        while(cur!=null || !stack.empty()){
            while(cur!=null){
                stack.add(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }

        return list;
    }
}

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.
在这里插入图片描述
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

Java O(n) Solution - Bucket Sort:

Idea is simple. Build a array of list to be buckets with length 1 to sort.

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {

        List<Integer>[] bucket = new List[nums.length + 1];
        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

        for (int n : nums) {
            frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
        }

        for (int key : frequencyMap.keySet()) {
            int frequency = frequencyMap.get(key);
            if (bucket[frequency] == null) {
                bucket[frequency] = new ArrayList<>();
            }
            bucket[frequency].add(key);
        }

        List<Integer> res = new ArrayList<>();

        for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
            if (bucket[pos] != null) {
                res.addAll(bucket[pos]);
            }
        }
        return res;
    }
}

560. Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
在这里插入图片描述
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Java Solution, PreSum + HashMap:

Solution 1. Brute force. We just need two loops (i, j) and test if SUM[i, j] = k. Time complexity O(n^2), Space complexity O(1). I bet this solution will TLE.

Solution 2. From solution 1, we know the key to solve this problem is SUM[i, j]. So if we know SUM[0, i - 1] and SUM[0, j], then we can easily get SUM[i, j]. To achieve this, we just need to go through the array, calculate the current sum and save number of all seen PreSum to a HashMap. Time complexity O(n), Space complexity O(n).

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int sum = 0, result = 0;
        Map<Integer, Integer> preSum = new HashMap<>();
        preSum.put(0, 1);
        
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (preSum.containsKey(sum - k)) {
                result += preSum.get(sum - k);
            }
            preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
        }
        
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/xw_Summer/article/details/86610868