zoukankan      html  css  js  c++  java
  • Leetcode 27. Remove Element

    27. Remove Element

    • Total Accepted: 129784
    • Total Submissions: 372225
    • Difficulty: Easy

    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.

    思路:遇到val等值的数就删除。


    代码:

    这个适合于不改变原来数的顺序和位置的情况:

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int i;
     5         for(i=0;i<nums.size();){
     6             if(nums[i]==val){
     7                 nums.erase(nums.begin()+i);
     8                 continue;
     9             }
    10             i++;
    11         }
    12         return nums.size();
    13     }
    14 };

    实际上,本题可以改变原来数的顺序,所以下面的写法也可以:

    写法一:begin指针只记录可以留下的数。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int begin=0,i=0;
     5         while(i<nums.size()){
     6             if(nums[i]!=val){
     7                 nums[begin++]=nums[i];
     8             }
     9             i++;
    10         }
    11         return begin;
    12     }
    13 };

    写法二:将当前最后的元素替换掉确认已经重复的元素,再对置换后的数进行判断。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int i=0,n=nums.size();
     5         while(i<n){
     6             if(nums[i]==val){
     7                 nums[i]=nums[--n];
     8             }
     9             else{
    10                 i++;
    11             }
    12         }
    13         return n;
    14     }
    15 };

    写法三:用count记录所有的不符合要求的数。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int count=0,i,n=nums.size();
     5         for(i=0;i<n;i++){
     6             if(nums[i]==val){
     7                 count++;
     8             }
     9             else{
    10                 nums[i-count]=nums[i];
    11             }
    12         }
    13         return n-count;
    14     }
    15 };
  • 相关阅读:
    Android中Handler原理
    微软柯塔娜(Cortana)的一句名言
    C# 单例模式的五种写法
    HTTP Status 404
    PLSQL中显示Cursor、隐示Cursor、动态Ref Cursor差别
    Android 开发之集成百度地图的定位与地图展示
    iOS知识点汇总
    优化报表系统结构之报表server计算
    淘宝中间的一像素线(手机端)
    解决yum升级的问题“There was a problem importing one of the Python modules”
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5678617.html
Copyright © 2011-2022 走看看