Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Last active July 6, 2022 22:41
Show Gist options
  • Save Turskyi/6b8855c981f3b7f572ea9ebcba53b3bb to your computer and use it in GitHub Desktop.
Save Turskyi/6b8855c981f3b7f572ea9ebcba53b3bb to your computer and use it in GitHub Desktop.
Given a sorted integer array, nums, remove duplicates from the array in-place such that each element only appears once. Once you’ve removed all the duplicates, return the length of the new array.
fun removeDuplicates(nums: IntArray): Int {
var counter = 0
for(i: Int in 1 until nums.size) {
// two pointers. one always at least one step back. first one is comparing two digits from index 0 and 1
if(nums[counter] != nums[i]) {
counter++
nums[counter] = nums[i]
}
}
return counter + 1
}
/*
Given an integer array nums sorted in non-decreasing order,
remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages,
you must instead have the result be placed in the first part of the array nums.
More formally, if there are k elements after removing the duplicates,
then the first k elements of nums should hold the final result.
It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment