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 };
原文地址:https://www.cnblogs.com/LCCRNblog/p/5034093.html