zoukankan      html  css  js  c++  java
  • 27. Remove Element 移除元素Easy

    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.


     

    思路分析:

      1.最终要求的是输出除给定值以外的其他数组中的值,所写方法需要返回的是这些值的总个数,即输入[3,2,2,3]==>输出:2,并且数组的新状态为[2,2,3,3];

      2.最近在复习排序算法,所以这个问题很亲切,其中也一种排序的影子,只不过是把特定的值而不是最大值放到最后,问题还有一个约束:只能用常数级的额外空间,即O(n)=1,所以不能通过额外的数组来记录给定值以外的值完成;

      3.因此,排序里面每一次循环里怎么把局部最大值移动到局部的最后,这里也可沿用,只不过,这里问题有其特殊性:值一旦已经确定了,不需要后续的一轮比较来确定(排序的时候最大值需要这样来确定),一旦遍历到就可以直接当做‘最大值’来移动到最左边,而且最大值只有一个,但特定值可以同时出现。


    C#代码: 

     1 public class Solution {
     2     public int RemoveElement(int[] nums, int val) {
     3         int j=nums.Length-1,len= nums.Length,i=0;
     4         while(j>=i){
     5                 if(nums[j]==val){
     6                     len--;
     7                     j--;
     8                     continue;
     9                 }
    10                 if(nums[i]==val){
    11                     int temp = nums[i];
    12                     nums[i] = nums[j];
    13                     nums[j] = temp;
    14                     len--;
    15                     j--;
    16                 }else{
    17                     i++;
    18                 }
    19                 if(i==j){
    20                     break;
    21                 }
    22         }
    23         return len;
    24     }
    25 }

     或者:

    public class Solution {
        public int RemoveElement(int[] nums, int val) {
            int len= nums.Length;
            for(int i=0;i<nums.Length;i++){
                if(i==len)break;
                if(nums[i]==val){
                    if(nums[len-1]==val){
                        len--;
                        i--;
                        continue;
                    }
                    int temp = nums[i];
                    nums[i] = nums[len-1];
                    nums[len-1] = temp;
                    len--;
                }
            }
            return len;
        }
    }
  • 相关阅读:
    [转]swift 学习资源 大集合
    [转]Swift 编程语言入门教程
    luogu 3375 KMP模板题
    我终于明白了的马拉车算法———感谢我们学校的大佬
    A*B problem(FFT)
    又是毕业季1&&又是毕业季2
    邻接表——最简单易懂的写法——向非我非非我大佬低头
    马拉车——Manacher一篇看上去很靠谱的理解(代码显然易懂)
    邻接表存储
    一直想写的关于tarjan算法的理解——向struct edge大佬低头
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6539993.html
Copyright © 2011-2022 走看看