秒杀removeDuplicates问题(Golang版本)
周末食欲不振,拿一道简单难度的题找找感觉,题目如下:
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. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
一个简单的思路就是通过遍历数组把非重复的元素保存到一个新的数组里面,然后再利用golang内置的copy方法,修改nums为非重复的:
func removeDuplicates(nums []int) int {
var res []int
for i := 0; i < len(nums); i++ {
if i == len(nums) - 1 || nums[i] != nums[i + 1] {
res = append(res, nums[i])
}
}
copy(nums, res)
fmt.Println(res)
return len(res)
}
或者只是用一个map来保存一个不重复的元素标识集合:
func removeDuplicates(nums []int) int {
seen := make(map[int]bool)
j := 0
for _, n := range nums {
if !seen[n] {
seen[n] = true
nums[j] = n
j++
}
}
return j
}
总结
由于golang的slice的删除比较麻烦, 所以我还是考虑用重新赋值的方式,很多时候我们必须深入到数据结构本身去思考赋值问题。