shriyanshi24jindal

Contains Duplicate

Mar 30th, 2026
142
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 6.86 KB | None | 0 0
  1. class Solution {
  2.  
  3. /** T(N) = O(N), O(N) */
  4. public boolean hasDuplicate(int[] nums) {
  5. Set<Integer> set = new HashSet<>();
  6. for(int ele : nums)
  7. set.add(ele);
  8.  
  9. // set size won't be same if array has duplicates, because in set we cannot store duplicate elements
  10. if(set.size() != nums.length)
  11. return true;
  12.  
  13. return false;
  14. }
  15.  
  16. /** T(N) = O(N*Log N), O(1) */
  17. public boolean hasDuplicate(int[] nums) {
  18. Arrays.sort(nums);
  19. for(int i=1; i<nums.length; i++)
  20. {
  21. if(nums[i-1] == nums[i])
  22. return true;
  23. }
  24. return false;
  25. }
  26.  
  27. /** T(N) = O(N), O(1) */
  28. // only if array has positive integers
  29. public boolean hasDuplicate(int[] nums)
  30. {
  31. for(int i=0; i<nums.length-1; i++)
  32. {
  33. int diff = Math.abs(nums[i+1] - nums[i]);
  34. if(diff == 1)
  35. continue;
  36. else
  37. return true;
  38. }
  39. return false;
  40. }
  41. }
RAW Paste Data Copied