Leet Code OJ 27. Remove Element [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 27. Remove Element [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
翻譯:
給定一個數組和一個值,在原地移除所有的這個值的實例,并且返回新的數組長度。
元素的順序可以被改變。而該數組在超過新長度的部分,可以不去管它。
分析:
我的做法是把所有非給定值的元素,交換到數組的前面位置。而這邊做了一些優化,即只把非指定值替換到前面,而不需要把給定值替換到后面。我創建了一個指針(數組下標),代表當前可作為寫入新值的數組位置,同時循環結束后,它也是新數組的長度。
代碼:
public class Solution {public int removeElement(int[] nums, int val) {int nextEmpty=0;for(int i=0;i<nums.length;i++){if(nums[i]!=val){nums[nextEmpty]=nums[i];nextEmpty++;}}return nextEmpty;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 27. Remove Element [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 83. Rem
- 下一篇: Leet Code OJ 58. Len