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);
         }
    }
  • 相关阅读:
    SQL 数据开发(经典)转贴
    2018学习计划 借鉴
    SQL数据库索引理解与应用【转贴--收藏】
    学生成绩信息表
    网址收录
    导出word文档 通过DocX组件
    Aspose.word
    C#编码规范
    远程连接ORACLE服务
    Request.Form()的使用
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7639642.html
Copyright © 2011-2022 走看看