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;
        }
  • 相关阅读:
    简单题
    bzoj2131
    bzoj1706
    bzoj3531
    bzoj3744
    bzoj2724
    bzoj3343
    bzoj1005
    编程中、遇到问题、bug多思考
    线上系统奇怪问题总结,性能问题不能依赖经验
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5045764.html
Copyright © 2011-2022 走看看