• [leetcode]27. Remove Element删除元素


    Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

    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.

    题意:

    给定某个值,要求删除数组中所有等于该值的元素。


    思路:

    指针i遍历数组,遇到非value的值,送到指针start那里去

    指针start从0开始,接收所有指针i送来的非value值

    扫完一遍后

    指针start所指的位置就是新“数组”的长度

    代码:

    1  public int removeElement(int[] nums, int target) {
    2         int start = 0;
    3         for (int i = 0; i < nums.length; ++i) {
    4             if (nums[i] != target) {
    5                 nums[start++] = nums[i];
    6             }
    7         }
    8         return index;
    9     }
  • 相关阅读:
    Binary Tree Paths
    Implement Stack using Queues
    Path Sum II
    Path Sum
    Plus One
    Add Digits
    Missing Number
    H-Index II
    H-Index
    Ugly Number II
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125368.html
Copyright © 2020-2023  润新知