Solution1: Run time complexity of Arrays.sort is O(nlogn), so total run time complexity is O(nlogn), constant space.
public class Solution { public boolean containsDuplicate(int[] nums) { if (nums == null || nums.length <= 1) { return false; } Arrays.sort(nums); int i = 0; int j = i + 1; while (j < nums.length) { if (nums[i] == nums[j]) { return true; } else { i++; j++; } } return false; } }Solution2: Run time complexity is O(n), space complexity is O(n).
public class Solution { public boolean containsDuplicate(int[] nums) { if (nums == null || nums.length <= 1) { return false; } HashSet set = new HashSet(); for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) { return true; } else { set.add(nums[i]); } } return false; } }Or
public class Solution { public boolean containsDuplicate(int[] nums) { if (nums == null || nums.length == 0) { return false; } HashSetset = new HashSet (); for (int i : nums) { if (!set.add(i)) { return true; } } return false; } }
No comments:
Post a Comment