zoukankan      html  css  js  c++  java
  • 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 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.

    Example:

    Given nums = [3,2,2,3], val = 3,
    
    Your function should return length = 2, with the first two elements of nums being 2.

    从一个数组中删除指定元素,而且也只能在当前数组中操作。这跟Remove Duplicates from Sorted Array一样的要求,所以思路也差不多。就是用两个指针,一个用于遍历,一个代表新数组添加元素。这题比去除重复元素那题要简单。

    class Solution {
        public int removeElement(int[] nums, int val) {
            if(nums==null||nums.length==0)
                return 0;
            int count=0;//该指针用于添加元素,i用于遍历数组
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=val)
                    nums[count++]=nums[i];
            }
            return count;
        }
    }
    
    
  • 相关阅读:
    阴影及定位
    选择器高级、样式及布局
    css的导入与基础选择器
    html知识
    ORM
    python实现进度条
    MySQL单表查询
    一、HTTP
    mysql4
    练习——MySQL
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8064111.html
Copyright © 2011-2022 走看看