zoukankan      html  css  js  c++  java
  • 27. Remove Element(双指针)

     

    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.

    Example 1:

    Given nums = [3,2,2,3], val = 3,
    
    Your function should return length = 2, with the first two elements of nums being 2.
    
    It doesn't matter what you leave beyond the returned length.
    

    Example 2:

    Given nums = [0,1,2,2,3,0,4,2], val = 2,
    
    Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
    
    Note that the order of those five elements can be arbitrary.
    
    It doesn't matter what values are set beyond the returned length.


    法1:

    统计出val的数量,把val 交换到后面。

     1 class Solution {
     2     public int removeElement(int[] nums, int val) {
     3         int i = 0;
     4         int j = nums.length-1;
     5         int cnt = 0;
     6         for(int k =0;k<nums.length;k++)
     7             if(nums[k]==val)
     8                 cnt++;
     9         if(cnt==0)
    10             return nums.length;
    11         while(i<nums.length-cnt||j>nums.length-cnt){
    12             while(i<nums.length-cnt&&nums[i]!=val) i++;
    13             while(j>nums.length-cnt&&nums[j]==val) j--;
    14             swap(nums,j,i);
    15         }
    16         return nums.length-cnt;
    17     }
    18     private void swap(int[] a,int i ,int j){
    19         int t = a[i];
    20         a[i] = a[j];
    21         a[j] =t;
    22     }
    23 }
    
    
     1 class Solution {
     2     public int removeElement(int[] nums, int val) {
     3         int m = 0;
     4         for(int i = 0;i<nums.length;i++){
     5             if(nums[i]!=val){
     6                 nums[m] = nums[i];
     7                 m++;
     8             }
     9         }
    10         return m;
    11     }
    12 }
  • 相关阅读:
    kettle部分传输场景应用(每个作业都实验过啦)
    Java设计模式之《适配器模式》及应用场景
    Mysql笔记
    Spring知识点
    Java基础系列-浅拷贝和深拷贝
    前端-javascript知识点
    前端-jquery知识点
    Java基础系列-substring的原理
    Java设计模式之《抽象工厂模式》及使用场景
    Java基础系列-Enum深入解析
  • 原文地址:https://www.cnblogs.com/zle1992/p/9003489.html
Copyright © 2011-2022 走看看