题目:
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.
//主要是Do not allocate extra space for another array,需要复用一个数组的内存空间
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
package mainimport ( "fmt")func sort_array_len(array []int) int { array_len := len(array) if array_len < 1 { return 0 } length := 0 last_element := array[0] for i := 0; i < array_len; i++ { if array[i] != last_element && i != 0 { length++ last_element = array[i] } } return length + 1}func remove_duplicate_element(array []int) int { array_len := len(array) if array_len < 1 { return 0 } length := 0 last_element := array[0] for i := 0; i < array_len; i++ { if array[i] != last_element && i != 0 { length++ last_element = array[i] array[length] = array[i] } } return length + 1}func main() { test_array := []int{2, 3, 5, 5, 5, 6, 8, 9} result_len := remove_duplicate_element(test_array) fmt.Println(result_len) fmt.Println(test_array[:result_len])}
输出结果:
6 [2 3 5 6 8 9]