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 };
  • 相关阅读:
    Linux ps 命令获取查询结果中的单列信息
    nowcoder(牛客网)普及组模拟赛第一场 解题报告
    Subway Pursuit (二分)(交互题)
    nowcoder(牛客网)OI测试赛2 解题报告
    NOIP提高组题目归类+题解摘要(2008-2017)
    CYJian的水题大赛2 解题报告
    数独问题
    题解 UVA11300 【Spreading the Wealth】
    实验吧web题:
    简单的sql语句
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5678617.html
Copyright © 2011-2022 走看看