Monday, August 24, 2015

[Duplicate] Contain Duplicate I

1. Example

a = [1,2,3,4,5] => False
b= [1,1,2,3,4,5]=>True
c= [1,1,1,2,3,4,5]=>True

2. Implementation
Duplicate + array of integer =>
Thought1: hashset =>O(n) , Sapce:O(n) for set
Thought2: sorted array and keep one called lastElement to compare with current and update if not same.Otherwise, duplicate happen => O(n log(n)), space O(1) for lastElement
Time efficient go with thought 1
Space efficient go with thought 2


//Time :O(n) go over the array and Space:O(n) set size
public class Solution
{
    public boolean containsDuplicate(int[] nums)
    {
         HashSet set = new HashSet();
         // valid the input
         if (nums == null || nums.length = 0)
         {
              return false;
         }



         for (int i = 0 ; i < nums.length; i++)
         {
              // NOTE: use add instead of contain to save one step of check
              if (! set.add(nums[i]))
              {
                   return true;
              }
         }
         return false;


    }
}

No comments:

Post a Comment