Sunday, August 20, 2017

LeetCode - 26. Remove Duplicates from Sorted Array

Source Link:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 

Question:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2]


Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 

My Solution: Note:
1. we need to return "the new length" and need to "modify the given array"
2. it doesn't matter what you leave beyond the new length (simple)
3. the array has been sorted (so only need one pass)
4. the value that we need to compare with
int index = nums[0];
5. a different value appears
if(nums[i] != index){
index = nums[i];       // change the value that we need to compare with
nums[count]=index; // modify the given array
count++;                   // the new length++
}

6. skip the case: nums[i] == index
7. return the new length
return count;

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...