zoukankan      html  css  js  c++  java
  • removeElement

    Description:

    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.

     Thoughts:

    首先我们需要两个计数指针,第一个指针pos它用来遍历数组,第二个指针length用来记录当前除去val元素后的长度。如果当前pos指针指向的值等于val,那么只把pos指针递增,否则说明当前的元素应该包含在新的数组中那么我们就把数组中length的位置的值赋值为pos指针所指向的值,然后将pos和length 的值都加1。

    以下是我的java代码:

    package easy.array;
    
    public class RemoveElement {
         public int removeElement(int[] nums, int val) {
                int length = 0;
                int pos = 0;
                while(pos < nums.length){
                    if(nums[pos] == val){
                        pos++;
                    }else{
    
                        nums[length] = nums[pos];
                        pos++;
                        length++;
                    }
                }
                return length;
            }
         public static void main(String[] args){
             RemoveElement re = new RemoveElement();
             int[] nums = {3,2,2,3};
             int val = 3;
             int returnnum = re.removeElement(nums, val);
             System.out.println(returnnum);
         }
    }
  • 相关阅读:
    hdu 1164 Eddy's research I
    hdu 3794 Magic Coupon
    hdu 1460 完数
    hdu 1201 18岁生日
    求一组整数中所有素数之和
    备忘录
    c判断括弧是否匹配
    N!大整数阶乘问题
    计算一个人从出生到现在活了多少天
    java web.xml配置详解(转)
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7639642.html
Copyright © 2011-2022 走看看