26. Remove Duplicates from Sorted Array
题目
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.
思路
数过去,和上一个数不一样就加1,得到总的计数就可以了。
代码
# @param {Integer[]} nums
# @return {Integer}
def remove_duplicates(nums)
if nums.empty? then return 0 end
p,last = 0,nums.at(0)
nums.each_with_index do |v,index|
if index != 0 and v != last then
p = p + 1
last = nums[p] = v
end
end
p + 1
end