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.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.

Solution:Two Pointers

Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public int removeElement(int[] nums, int val) {
        int new_i = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == val) continue;
            nums[new_i++] = nums[i];
        }
        return new_i;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評(píng)論 0 33
  • 人人只知道周星馳,但卻不知道當(dāng)初提攜他的那個(gè)人。說(shuō)起這個(gè)人,他曾經(jīng)也是娛樂(lè)圈的佼佼者,占領(lǐng)了大半個(gè)娛樂(lè)圈,但是時(shí)光...
    66CQcq66閱讀 121評(píng)論 0 0
  • 丫頭: 現(xiàn)在是2012年11月17日,我窩在宿舍里給三年后的你寫(xiě)下這封信,此刻鴻雁那丫頭正在一邊聽(tīng)歌一邊修改那篇把...
    九夏姑娘閱讀 3,705評(píng)論 0 5
  • 信任,分人。分階段。 為你好,不是長(zhǎng)久。最后,一切回歸原地。靜靜的享受這些的是是非非。
    uiu閱讀 195評(píng)論 0 1
  • 感激101-026 感激我今天看到,在我在意的人面前和場(chǎng)合里,我不是放松的狀態(tài),表面上看是我追求完美,本質(zhì)是,我覺(jué)...
    我和榕樹(shù)閱讀 228評(píng)論 0 0

友情鏈接更多精彩內(nèi)容