【C++】AOJ基础题 ITP2_4_D Unique

Unique

For a sequence of integers A = {a0, a1, …, an−1} which is sorted by ascending order, eliminate all equivalent elements.

Input

A sequence is given in the following format.

n
a0 a1 , ..., an−1

Constraints

  • 1 ≤ n ≤ 100,000
  • −1000,000,000 ≤ ai ≤ 1,000,000,000
  • a0 ≤ a1 ≤…≤ an−1

Output

Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character.

Sample Input

4
1 2 2 4

Sample Output

1 2 4

問題を解く

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <vector>


using namespace std;

int main() {
	int n = 0;
	int m = 0;
	int b = 0;
	int e = 0;
	int k = 0;

	vector<int>a;

	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> m;
		a.push_back(m);
	}

	a.erase(unique(a.begin(), a.end()), a.end());

	cout << a[0];
	for (int i = 1; i < a.size(); i++)
	{
		cout << " " << a[i];
	}
	cout << endl;

	return 0;
}

总结

  • 很基础的题,这里需要mark一下vector里erase和unique的用法:
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
template <class ForwardIterator>
  ForwardIterator unique (ForwardIterator first, ForwardIterator last)
{
  if (first==last) return last;

  ForwardIterator result = first;
  while (++first != last)
  {
    if (!(*result == *first))  // or: if (!pred(*result,*first)) for version (2)
      *(++result)=*first;
  }
  return ++result;
}
  • 可以看到unique()函数找的是“相邻”重复的元素,并将重复的元素放到尾部,然后返回指向第一个重复元素的迭代器;
  • 所以使用unique之前一定要进行sort()排序,最后用erase进行删除。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值