這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
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.
翻譯:給定一個排序好了的數組,重複資料刪除的位置,使每個元素只顯示一次並返回新的長度。不要為另一個數組分配額外的空間,您必須使用常量記憶體來進行此操作。
思路:就是去除數組中重複的數,不過要求不能重新分配記憶體,所以只能在原數組中操作.
1.首先我們知道排序的數組,nums[i+1]>=nums[i];
2.我們可以設定一個標誌count,為重複數位數量,遍曆數組,當nums[i]==nums[i-1]時,count++;不等時,使nums[i-count]==nums[i]
3.解釋一下i-count,它的計算值是當前元素下標-已遍曆重複數數量,即為剩下的唯一數數量
4.遍曆結束,len(nums)-count就是剩下的唯一數數量
golang代碼:
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
題目:Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
翻譯:給定一個數組和一個值,刪除該值的所有執行個體,並返回新的長度。不要為另一個數組分配額外的空間,您必須使用常量記憶體來進行此操作。元素的順序可以改變。
思路:這題比較簡單,簡單說下,就是要返回不和val值相等的數組元素數量。設定返回結果result初始值為0,遍曆數組,如果值和給定的val值不同,給nums[result]賦值為nums[i],並且result加1。
golang代碼:
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}