zoukankan      html  css  js  c++  java
  • Remove Element leetcode java

    问题描述:

    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.

    问题分析:给定一个数组,一个value值,从这个数组中删除所有值为value的元素,并返回数组length

    算法:

    方法一:借助另外一个list,耗费空间

    public static int removeElement(int nums[],int val){
    
            List<Integer> list = new ArrayList<Integer>(); //将数据暂时存放在list中
            for (int i = 0; i < nums.length; i++) {
                if(nums[i] != val)
                    list.add(nums[i]);
            }
            
            if(list.size() != 0){
                for (int i = 0; i < list.size(); i++) { //再将list中的数据写回数组中
                    nums[i] = list.get(i);
                }
            }
            
            return list.size() ; //返回数组length
        }

     方法二:采用两个指针,不需要额外空间,数组原地做修改

    public int removeElement(int[] nums, int val) {
            //原地修改,不需要额外的空间
            int newindex = 0;
            for (int i = 0; i < nums.length; i++) {
                if(nums[i] != val)
                    nums[newindex++] = nums[i];
            }
            
            return newindex;
        }
  • 相关阅读:
    令Django 视图有默认 login_required
    令Django 视图有默认 login_required
    Python 资源
    Python 资源
    小米3 日历 同步google日历
    小米3 日历 同步google日历
    sql语句 case
    DDOSIM安装
    DDos工具tfn2k的编译
    RPM和YUM
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5045764.html
Copyright © 2011-2022 走看看