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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 人人只知道周星驰,但却不知道当初提携他的那个人。说起这个人,他曾经也是娱乐圈的佼佼者,占领了大半个娱乐圈,但是时光...
    66CQcq66阅读 1,058评论 0 0
  • 丫头: 现在是2012年11月17日,我窝在宿舍里给三年后的你写下这封信,此刻鸿雁那丫头正在一边听歌一边修改那篇把...
    九夏姑娘阅读 8,954评论 0 5
  • 信任,分人。分阶段。 为你好,不是长久。最后,一切回归原地。静静的享受这些的是是非非。
    uiu阅读 1,355评论 0 1
  • 感激101-026 感激我今天看到,在我在意的人面前和场合里,我不是放松的状态,表面上看是我追求完美,本质是,我觉...
    我和榕树阅读 1,558评论 0 0

友情链接更多精彩内容