zoukankan      html  css  js  c++  java
  • Leetcode题解(八)

    26、Remove Duplicates from Sorted Array

    题目

    直接上代码,方法很简单:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            const int size = nums.size();
            int currentValue,index,validIndex;
    
    
            if(size <= 1)
                return size;
    
            currentValue = nums[0];
            index = 1;
            int count = 1;
            validIndex = 1;
    
            for (;index < size;index++)//因为数组已经排序,所以可以用一个变量保存当前比较的值
            {
                if(currentValue != nums[index])
                {
                    currentValue = nums[index];
                    nums[validIndex] = nums[index];
                    validIndex++;
                    count++;
                }
            }
    
            return count;
    
        }
    };

    ---------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------

    27、Remove Element

    题目

    算法很简单,只是在实现的时候,为了避免多次平移,需要从数组从尾到首的进行处理,代码如下:

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int size = nums.size();
     5         if(size == 0)
     6             return size;
     7 
     8         int index = size -1;
     9         
    10 
    11         while (nums[index] == val)
    12         {
    13             index--;
    14             
    15         }
    16         int end = index;
    17         for (;index >= 0;index--)
    18         {
    19             if(nums[index] == val)
    20             {
    21                 nums[index] = nums[end];
    22                 end--;
    23             }
    24         }
    25 
    26         return end+1;
    27 
    28     }
    29 };
  • 相关阅读:
    httpd-2.2 配置及用法完全攻略
    在 Ubuntu 16.04 上安装 LEMP 环境之图文向导
    Zookeeper集群搭建
    smem – Linux 内存监视软件
    X.Org可能将失去它的域名x.org
    Docker 容器测试全探索
    Unix操作系统中UUCP知识详细讲解
    常用的Git Tips
    Unix操作系统中UUCP知识详细讲解
    将博客搬至CSDN
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/5034093.html
Copyright © 2011-2022 走看看