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 }
  • 相关阅读:
    网页快捷键
    2016年5月3日15:55:23笔记
    【编程的乐趣-用python解算法谜题系列】谜题一 保持一致
    重温离散系列②之良序原理
    重温离散系列①之什么是证明
    浅谈栈和队列
    [leetcode]16-最接近的三数之和
    [leetcode] 4-寻找两个有序数组的中位数
    英语句子的基本结构【转】
    [leetcode] 11-盛最多水的容器
  • 原文地址:https://www.cnblogs.com/zle1992/p/9003489.html
Copyright © 2011-2022 走看看