秒殺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的刪除比較麻煩, 所以我還是考慮用重新賦值的方式,很多時候我們必須深入到數據結構本身去思考賦值問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章