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 };
  • 相关阅读:
    goroutine
    golang package log
    golang单元测试
    golang 文件操作
    go递归打印指定目录下的所有文件及文件夹
    go语言切片作为函数参数的研究
    go数据类型之基本类型
    结束了
    codeforces358D Dima and Hares【dp】
    codeforces1081G Mergesort Strikes Back【期望dp+脑洞】
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/5034093.html
Copyright © 2011-2022 走看看