From 629900731c0772da3a86f09455968fee1889644a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Fri, 26 Oct 2018 23:51:55 +0800 Subject: [PATCH] Create 026. Remove Duplicates from Sorted Array.md --- 026. Remove Duplicates from Sorted Array.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 026. Remove Duplicates from Sorted Array.md diff --git a/026. Remove Duplicates from Sorted Array.md b/026. Remove Duplicates from Sorted Array.md new file mode 100644 index 0000000..3f83893 --- /dev/null +++ b/026. Remove Duplicates from Sorted Array.md @@ -0,0 +1,21 @@ +# [026. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) + +# 思路 +由于是已经排序好的数组,所以相同的数肯定是相邻的,遍历数组时跳过与上一个数重复的数即可。 +可以用一个count记录在下标count及之前是没有重复的数组, count初始化为0,然后从前往后遍历,若a[i]==a[count]说明重复,不更新count, +否则应该让count++。注意单独判断空数组。 + +# C++ +``` c++ +class Solution { +public: + int removeDuplicates(vector& nums) { + if(nums.empty()) return 0; + int count = 0; + for(int i = 1; i < nums.size(); i++){ + if(nums[i] != nums[count]) nums[++count] = nums[i]; + } + return count+1; + } +}; +```