2nd__26. Remove Duplicates from Sorted Array__【400_LeetCode之路】

 

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {

		if (nums.size() == 0)
			return 0;

		int res = 1;
		int index = nextDifferentCharacterIndex(nums, 1);
		int i = 1;
		while (index < nums.size()) {
			res++;
			nums[i++] = nums[index];
			index = nextDifferentCharacterIndex(nums, index + 1);
		}

		return res;
	}
private:
	int nextDifferentCharacterIndex(const vector<int> &nums, int p) {
		for (; p < nums.size(); p++)
			if (nums[p] != nums[p - 1])
				break;
		return p;
	}
};









//************************************************************
//  完整程序
//************************************************************
 /// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/
 /// Author : liuyubobobo
 /// Time   : 2016-12-06


 //#include <iostream>
 //#include <vector>
 //#include <cassert>
 //#include <stdexcept>

 //using namespace std;

 / Two pointers
 / Time Complexity:  O(n)
 / Space Complexity: O(1)
 //class Solution {
 //public:
 //	int removeDuplicates(vector<int>& nums) {

 //		if (nums.size() == 0)
 //			return 0;

 //		int res = 1;		//初始被保存下来的个数是1,后面被保存的数可能逐渐增加
 //		int index = nextDifferentCharacterIndex(nums, 1);		//初始使用 nextDifferentCharacterIndex 的函数输入值要从第二个数即 角标=1 开始
 //		//这是 index 的初始化,方法很不错


 //		int i = 1;		//i从1开始,
 //		while (index < nums.size()) {
 //			res++;		//如果上面的循环开始,意味着第一次 nextDifferentCharacterIndex 返回了值,所以 res++;且nums 的第二数   nums[i++] = nums[index]
 //			nums[i++] = nums[index];	//这个是重复利用 nums 原有的内存,不用额外开辟新内存
 //			index = nextDifferentCharacterIndex(nums, index + 1);	//每次进入while 循环,传入的 p值  都要用 index+1,不能用 index,因为要进行新一轮的对比 nums[p] != nums[p - 1]
 //		}

 //		return res;
 //	}


 私有函数
 判定下一个数和当前的数是否相等,如果不相等,就break,且 return p,返回的是最终不相等的那个数的角标
 //private:
 //	int nextDifferentCharacterIndex(const vector<int> &nums, int p) {
 //		for (; p < nums.size(); p++)		//for不需要开始条件,  p < nums.size() 是指要从当前数的下一个一直遍历到数组的结尾
 //			if (nums[p] != nums[p - 1])
 //				break;        //break 只是跳出if 循环而没有跳出函数 nextDifferentCharacterIndex,break后需要 return p
 //		return p;
 //	}
 //};


 //int main() {

 //	vector<int> nums1 = { 1, 1, 2, 1 };
 //	cout << Solution().removeDuplicates(nums1) << endl;


 //	system("pause");
 //	return 0;
 //}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值