★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-exssrkvh-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array nums and a value val, remove all instances of that value in-place and return the new length.git
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.github
The order of elements can be changed. It doesn't matter what you leave beyond the new length.數組
Example 1:微信
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length.
Example 2:函數
Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = , with the first five elements of containing , , , , and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.5nums0130
Clarification:this
Confused why the returned value is an integer but your answer is an array?spa
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.code
Internally you can think of this:htm
// nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
給定一個數組 nums 和一個值 val,你須要原地移除全部數值等於 val 的元素,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
元素的順序能夠改變。你不須要考慮數組中超出新長度後面的元素。
示例 1:
給定 nums = [3,2,2,3], val = 3, 函數應該返回新的長度 2, 而且 nums 中的前兩個元素均爲 2。 你不須要考慮數組中超出新長度後面的元素。
示例 2:
給定 nums = [0,1,2,2,3,0,4,2], val = 2, 函數應該返回新的長度 , 而且 nums 中的前五個元素爲 , , , , 4。 注意這五個元素可爲任意順序。 你不須要考慮數組中超出新長度後面的元素。 50130
說明:
爲何返回數值是整數,但輸出的答案是數組呢?
請注意,輸入數組是以「引用」方式傳遞的,這意味着在函數裏修改輸入數組對於調用者是可見的。
你能夠想象內部操做以下:
// nums 是以「引用」方式傳遞的。也就是說,不對實參做任何拷貝 int len = removeElement(nums, val); // 在函數裏修改輸入數組對於調用者是可見的。 // 根據你的函數返回的長度, 它會打印出數組中該長度範圍內的全部元素。 for (int i = 0; i < len; i++) { print(nums[i]); }
1 class Solution { 2 //當 nums[j]與給定的值相等時,遞增 j 以跳過該元素。 3 //只要 nums[j]不等於val咱們就複製nums[j]到nums[i],並同時遞增兩個索引。 4 //重複這一過程,直到j到達數組的末尾,該數組的新長度爲 i。 5 func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 6 //定義返回的數組新長度 7 var i:Int=0 8 //遍歷數組 9 for num in nums 10 { 11 if num != val 12 { 13 nums[i]=num 14 i+=1 15 } 16 } 17 return i 18 } 19 }
高效版本
class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { var i = 0, j = nums.count - 1 while i <= j { if nums[i] == val { //根據數組索引互換兩個元素 nums.swapAt(i, j) j -= 1 } else { i += 1 } } return j + 1 } }