Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
A:
--------Sol : 用Set , use O(n) extra space O(n) time---------
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet(); for(int i :nums){ if(set.contains(i)) return true; set.add(i); } return false; } }
-------Sol 2: manipulate nums, , use O(1) space, and O(n) time ----------------
每次按照某一位的 bit分开nums[], 然后再继续分,直到最后32bit还一样,就true,否则false
No comments:
Post a Comment