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);
         }
    }
  • 相关阅读:
    kvm虚拟机添加网卡
    rsync搭建
    hadoop副本数三个变为一个
    nginx日志ip提取参数介绍
    expect使用
    全球语言排行版查询
    mysql忘记密码(跳过权限修改)
    数据备份从阿里云主机(外网主机)拉取到本地服务器
    nginx+keepalived IP飘移(高可用)
    负载均衡配置
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7639642.html
Copyright © 2011-2022 走看看