当前位置 博文首页 > 令狐_JackieHao的博客:【LeetCode-每日一题】移除元素

    令狐_JackieHao的博客:【LeetCode-每日一题】移除元素

    作者:[db:作者] 时间:2021-07-13 10:06

    【LeetCode-每日一题】

    移除元素

      • 给定 nums = [0,1,2,2,3,0,4,2], val = 2,

        函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

        注意这五个元素可为任意顺序。

        你不需要考虑数组中超出新长度后面的元素。

    package code01数组.code02移除元素;
    //使用双指针,将需要的元素甩到数组最后一位去,在收缩长度
    public class Solution {
        public static int removeElement(int[] nums, int val) {
            int n=nums.length,left=0,right=0;
            while (right<n){
                if (nums[right]==val){
                    nums[right]=nums[n-1];
                    n--;
                }else {
                    right++;
                }
            }
            return n;
        }
    
        public static void main(String[] args) {
            int [] nums= new int[]{3,2,2,3};
            int val=3;
            int lenth=removeElement(nums,val);
            for (int i=0;i<lenth;i++){
                System.out.println(nums[i]);
            }
        }
    }
    
    
    
    cs