This is a creation in Article, where the information may have evolved or changed.
26.Remove Duplicates from Sorted Array
Title: Given A sorted array, remove the duplicates in place such, all element appear only once and return the new length.
Do the allocate extra space for another array, and you must does this on place with constant memory.
Translation: Given a sorted array, delete the duplicate positions so that each element is displayed only once and returns the new length. Do not allocate additional space for another array, you must use constant memory to do this.
The idea: is to remove the number of repetitions in the array, but requires that the memory cannot be reassigned, so it can only operate in the original array.
1. First we know the sorted array,nums[i+1]>=nums[i];
2. We can set a flag count, for the number of repetitions, iterate over the array, when Nums[i]==nums[i-1], count++; unequal, make nums[i-count]==nums[i]
3. Explain i-count, whose calculated value is the current element subscript-the number of traversed repetitions, that is, the remaining unique number
4. The end of the traversal, Len (nums)-count is the only number remaining
Golang Code:
package mainimport ( "fmt")func main() { nums := []int{1, 1, 5, 6, 6, 6} fmt.Println(removeDuplicates(nums))}func removeDuplicates(nums []int) int { count := 0 for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { count++ } else { nums[i-count] = nums[i] } } return len(nums) - count}
#27. Remove Element
Title: Given An array and a value, remove all instances of this value in place and return the new length.
Do the allocate extra space for another array, and you must does this on place with constant memory.
The order of elements can be changed. It doesn ' t matter what are you leave beyond the new length.
Translation: Given an array and a value, delete all instances of the value and return the new length. Do not allocate additional space for another array, you must use constant memory to do this. The order of the elements can be changed.
Idea: This question is relatively simple, simply say, is to return the number of array elements that are not equal to the Val value. Set the return result to the initial value of 0, iterate through the array, if the value is different from the given Val value, assign the value to Nums[result] nums[i], and result adds 1.
Golang Code:
package mainimport ( "fmt")func main() { nums := []int{1, 2, 1, 3} fmt.Println(removeElement(nums, 2))}func removeElement(nums []int, val int) int { var result int for i := 0; i < len(nums); i++ { if nums[i] != val { nums[result] = nums[i] result++ } } return result}