美文网首页
[LeetCode]No.27 Remove Elements

[LeetCode]No.27 Remove Elements

作者: yuansc | 来源:发表于2016-10-08 14:26 被阅读12次

    链接: https://leetcode.com/problems/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 in place with constant memory.
    The order of elements can be changed. It doesn't matter what you leave beyond the new length.
    **Example:**Given input array *nums* = [3,2,2,3]
    , *val* = 3
    
    Your function should return length = 2, with the first two elements of *nums* being 2.
    

    分析:
    本题要求不另开辟内存给新的数组,所以只能在原先数组上进行操作,那只有循环来校验每个元素,如果不是的话,就将元素往前移动。

    public class Solution {
        public int removeElement(int[] nums, int val) {
            int j=0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=val){
                    nums[j] = nums[i];
                    j++;
                }
            }
            return j;
        }
    }
    

    两个变量 i, j
    i用来表示循环到哪个元素
    j表示替换到哪个元素
    而最终要的就是新的数组长度,所以返回j即可。

    相关文章

      网友评论

          本文标题:[LeetCode]No.27 Remove Elements

          本文链接:https://www.haomeiwen.com/subject/vkmuyttx.html