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;
        }
    }
  • 相关阅读:
    转:Omnet++ 4.0 installation for Ubuntu
    转:myeclipse假死的解决方案
    omnet++ 4.0下使用XML的例子
    转:Microsoft JET Database Engine (0x80004005) 未指定的错误的完美解决
    C# 数据库删除操作错误报错 System.Data.SqlClient.SqlException (0x80131904)
    Windows 7 转移用户文件夹
    CentOS自动登录Gnome
    Archlinux GRUB2 配置
    Archlinux 登录管理器切换
    html2chm工具1.0发布
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6539993.html
Copyright © 2011-2022 走看看