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;
        }
    }
  • 相关阅读:
    [记录]Python2.7使用argparse模块
    [记录]MySQL读写分离(Atlas和MySQL-proxy)
    [记录]Shell中的getopts和getopt用法
    [记录]CentOS搭建SVN服务器(主从同步)
    [记录]Zabbix3.4配置监控Oracle12c的存活状态和表空间使用率
    [记录]一则清理MySQL大表以释放磁盘空间的案例
    [原创]Oracle 12c的备份和恢复策略
    Linux awk用法
    Oracle数据库学习笔记
    oracle无法删除当前连接用户方法
  • 原文地址:https://www.cnblogs.com/codingHeart/p/6539993.html
Copyright © 2011-2022 走看看