我是靠谱客的博主 个性草丛,最近开发中收集的这篇文章主要介绍LeetCode 27. Remove Element,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Description:
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.

Solution:
和上一题26类似
这种可以称为双指针,一个指向当前遍历的值,一个指向数组待放入的位置,只需要走一遍,速度很快。所以用时0ms,打败了100% JAVA submissions

public int removeElement(int[] nums, int val) {
        if(nums.length == 0) return 0;
        int count = 0;
        int cur = 0;
        int i = 0;
        while(i < nums.length){
            if(nums[i] != val){
                count++;
                nums[cur++] = nums[i];
            }
            ++i;
        }
        return count;

    }

最后

以上就是个性草丛为你收集整理的LeetCode 27. Remove Element的全部内容,希望文章能够帮你解决LeetCode 27. Remove Element所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部