26. Remove Duplicates from Sorted Array

2018/04/07 leetcode 共 982 字,约 3 分钟

Title

the problem link

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

返回一个数组不冗余的元素,两个指针。注意破坏原来数组没有关系

Solution

//cpp:
#include<iostream>
#include<stdio.h>
#include<string>
#include<vector>
#include<algorithm>
#include<cstring>
#include<unordered_map>
#include<functional>
using namespace std;

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		if (nums.size() == 0)
			return 0;
		int i = 0;
		for (int j = 1; j < nums.size(); j++) {
			if (nums[j] != nums[i]) {
				i++;
				nums[i] = nums[j];
			}
		}
		return i + 1;
	}
};
int main()
{
	freopen("D:/in.txt", "r", stdin);
	Solution a;
	vector<int> v = { 1,1,2 };
	cout<<a.removeDuplicates(v);
	return 0;
}

Search

    Table of Contents