去除重复数字:HardDuplicateRemover

Problem Statement
We have a sequence of integers, and we would like to remove all duplicate elements from this sequence. There may be multiple ways to perform this task.
For example, given the sequence { 1, 2, 1, 3 }, we could end up with either { 1, 2, 3 } or { 2, 1, 3 } as the remaining sequence, depending on which duplicate 1 we remove from the original sequence.
For this problem, we want to return the lexicographically first of of all possible remaining sequences.
A sequence S1 comes before sequence S2 lexicographically if and only if S1 has a smaller value than S2 at the lowest index at which the two sequences differ (so, for example, { 1, 2, 3 } comes before { 2, 3, 1 }).
You will be given a int[] sequence. Return a int[] containing the sequence after all the duplicates are removed. See the examples for further clarification.
Definition
Class:HardDuplicateRemover
Method:process
Parameters:int[]
Returns:int[]
Method signature:int[] process(int[] sequence)
(be sure your method is public)
Constraints
sequence will have between 1 and 50 elements, inclusive.-Each element of sequence will be between 1 and 1000, inclusive.
Examples
0){5, 6, 5, 1, 6, 5}
Returns: {1, 6, 5 }
There are six different ways to remove duplicates (remaining numbers are marked by ‘*’):
{ *5, *6,? 5, *1,? 6,? 5},
{ *5,? 6,? 5, *1, *6,? 5},
{? 5, *6, *5, *1,? 6,? 5},
{? 5,? 6, *5, *1, *6,? 5},
{? 5, *6,? 5, *1,? 6, *5},
{? 5,? 6,? 5, *1, *6, *5}.
The last variant is the lexicographically first.
1){3, 2, 4, 2, 4, 4}
Returns: {3, 2, 4 }
2){6, 6, 6, 6, 6, 6}
Returns: {6 }
3){1, 3, 2, 4, 2, 3}
Returns: {1, 2, 4, 3 }
4){5, 4, 1, 5}
Returns: {4, 1, 5 }

网上给的思路大多数如下,但我发现这种方案只能处理官方给的案例,不能处理所有案例,如6644。原因在于过早剪枝。事实上,本题但凡过早剪枝了,就有极大可能是会出错的。

/* 每次从头遍历,取当前遇到的最小的数字,直到遇到唯一数字/结尾跳出循环;给出的用例都能通过,但无法正确处理重复大数在前,小数字在后的情况,见case6 */
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void removeOneDuplicateElement(const int element, vector <int>& v) {
     /* delete the other temp_v[min_idx] */
    auto it = find(v.begin(), v.end(), element);
    while (it != v.end()) {
   
        v.erase(it);
        it = find
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值