leetcode刷題記錄Array篇(26&27~Remove Element)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.