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;
        }
    }
  • 相关阅读:
    xhEditor入门基础
    【Scala-ML】使用Scala构建机器学习工作流
    POJ 2482 Stars in Your Window(线段树)
    Xcode6 UIWebView与JavaScript交互(issue fix)
    poj1159--Palindrome(dp:最长公共子序列变形 + 滚动数组)
    把握linux内核设计思想(十二):内存管理之slab分配器
    Andriod DiskLruCache的使用案例
    Lambda 表达式的演示样例-来源(MSDN)
    HDU 4857 topological_sort
    Thinking in React(翻译)
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6539993.html
Copyright © 2011-2022 走看看