fueanta

LeetCode 26: Remove Duplicates from Sorted Array.

Mar 24th, 2020
186
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a sorted array nums, remove the duplicates in-place such that each element appear only once and
  3. return the new length. Do not allocate extra space for another array, you must do this by modifying
  4. the input array in-place with O(1) extra memory.
  5.  
  6. Examples:
  7. ---------
  8. Given nums = [1,1,2],
  9.  
  10. Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
  11.  
  12. It doesn't matter what you leave beyond the returned length.
  13. -----------------------------------------------------------------------
  14. Given nums = [0,0,1,1,1,2,2,3,3,4],
  15.  
  16. Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
  17.  
  18. It doesn't matter what values are set beyond the returned length.
  19.  
  20. Clarification:
  21. --------------
  22. Confused why the returned value is an integer but your answer is an array?
  23. Note that the input array is passed in by reference, which means modification to the input array will be
  24. known to the caller as well. Internally you can think of this:
  25.  
  26. // nums is passed in by reference. (i.e., without making a copy)
  27. int len = removeDuplicates(nums);
  28.  
  29. // any modification to nums in your function would be known by the caller.
  30. // using the length returned by your function, it prints the first len elements.
  31. for (int i = 0; i < len; i++) {
  32.     print(nums[i]);
  33. }
  34. */
  35.  
  36. namespace Problems.LeetCode.Array.RemoveDuplicatesfromSortedArray_26
  37. {
  38.     public class Solution
  39.     {
  40.         /// <summary>
  41.         ///     Removes duplicate numbers from a sorted array.
  42.         ///     Uses two pointers.
  43.         ///     Time complexity : O(n)
  44.         ///     Space complexity : O(1)
  45.         /// </summary>
  46.         /// <param name="nums">An array of integers.</param>
  47.         public int RemoveDuplicates(int[] nums)
  48.         {
  49.             if (nums.Length == 0) return 0;
  50.  
  51.             var length = 1;
  52.  
  53.             for (var i = 1; i < nums.Length; i++)
  54.                 if (nums[i] > nums[length - 1])
  55.                     nums[length++] = nums[i];
  56.  
  57.             return length;
  58.         }
  59.     }
  60. }
RAW Paste Data