Java O(n) solution using hash table beats 97%


  • 0
    J

    Use a hash table int[] hash to store the frequency of each value from 1 to n.

    public class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            int len = nums.length;
            int[] hash = new int[len + 1]; // 0 - len
            for(int num : nums) {
                hash[num]++;
            }
            List<Integer> list = new ArrayList<>();
            for(int i = 1; i <= len; i++) {
                if(hash[i] == 2)
                    list.add(i);
            }
            return list;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.