Question: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
My answer:
Basic logic: swap the 1st duplicate element with the 1st different one. firstDuplicateIndex is not necessary here, we can use variable count only to complete the function. But I'd like to keep it here so that code is readable.
class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length < 1) { return 0; } int temp = nums[0]; int firstDuplicateIndex = 0; int count = 1; for (int i = 1; i < nums.length; i ++) { if (temp != nums[i]) { firstDuplicateIndex ++; nums[firstDuplicateIndex] = nums[i]; count ++; temp = nums[i]; } } return count; } }
No comments:
Post a Comment