首页 > 试题广场 >

删除数组中的重复项

[编程题]删除数组中的重复项
  • 热度指数:1864 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个数组,你需要删除其中重复出现的元素,只保留最后一次出现的重复元素,使得每个元素只出现一次,返回新数组,并保证新数组中的元素顺序与原数组一致。
示例1

输入

[3,5,8,2,3,8]

输出

[5,2,3,8]
示例2

输入

[1,1,1,2,1]

输出

[2,1]

备注:
重复元素仅保留最后一次,原数组元素顺序需要与新数组保持一致。

哈希表

1.用哈希表顺序保存每个数值在数组中出现的位置;
2.顺序遍历数组arr,对于arr[i],只有当i是arr[i]最后一次出现的位置时才添加进结果数组。
#
# 删除重复元素
# @param array int整型一维数组 
# @return int整型一维数组
#
from collections import defaultdict

class Solution:
    def removeDuplicate(self , array ):
        # write code here
        m = defaultdict(lambda: [])
        for i in range(len(array)):
            m[array[i]].append(i)
        res = []
        for i, num in enumerate(array):
            if len(m[num]) == 1:
                res.append(num)
            else:
                if i == m[num][-1]:
                    res.append(num)
        return res
不保留所有位置,仅保留最后一个位置也可以,能够节省一点空间
import java.util.*;


public class Solution {
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public int[] removeDuplicate (int[] array) {
        // write code here
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < array.length; i++){
            map.put(array[i], i);
        }
        int[] res = new int[map.size()];
        int index = 0;
        for(int i = 0; i < array.length; i++){
            if(map.get(array[i]) == i){
                res[index++] = array[i];
            }
        }
        return res;
    }
}

编辑于 2022-02-21 17:23:53 回复(0)
先反着存入LinkedHashSet,再反着存入结果数组


 /**
     * 删除重复元素
     * @param array int整型一维数组
     * @return int整型一维数组
     */
    public static int[] removeDuplicate ( int[] array){
        // write code here
        LinkedHashSet<Integer> linkedHashSet=new LinkedHashSet<Integer>();
        for (int i = array.length-1; i>=0; i--) {
            linkedHashSet.add(array[i]);
        }
        int newArr[] = new int[linkedHashSet.size()];
        Iterator iterator=linkedHashSet.iterator();
        int i=linkedHashSet.size()-1;
        while (iterator.hasNext()){
            newArr[i]= (int) iterator.next();
            i--;
        }
        return newArr;
    }

发表于 2022-06-04 20:58:20 回复(0)
用linkedhashset反着存进数组就行了
发表于 2022-03-24 16:45:01 回复(0)
Set,从后往前
import java.util.*;


public class Solution {
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public int[] removeDuplicate (int[] array) {
        // write code here
        int len = array.length;
        if(len==0||len==1) return array;
        int j=len-1;
        Set<Integer> set = new HashSet<>();
        for(int i=len-1;i>=0;--i){
            if(set.contains(array[i])){
                continue;
            }else{
                set.add(array[i]);
                array[j--]=array[i];
            }
        }
        return Arrays.copyOfRange(array,++j,len);
    }
}



发表于 2022-03-16 21:20:41 回复(0)
从后往前遍历,hashmap key 为元素值为boolean ,如果使用了元素就标记为true,下次遇到直接跳过
发表于 2022-03-03 20:23:33 回复(0)
先转成list,利用list的remove方法遍历去重
public int[] removeDuplicate (int[] array) {
        // write code here
   
    List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
    System.out.println(list.size());
        for(int i=0;i<list.size();i++){
        for(int j=1+i;j<list.size();j++){
            if(list.get(i)== list.get(j)) {
            list.remove(i);
            }
            }
        }
        int [] ary =new int[list.size()];
        for(int k=0;k<list.size();k++){
        ary[k] =list.get(k);
        }
return ary;
    }
发表于 2022-02-21 16:54:10 回复(0)
哈希表统计次数
次数为1的就输出
不为1则次数减一,这样便可保留顺序了(ps:终于自己写出来一道题了,继续加油吧。)

#
# 删除重复元素
# @param array int整型一维数组 
# @return int整型一维数组
#
class Solution:
    def removeDuplicate(self , array ):
        dic = {}
        for i in array:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        res = []
        for i in array:
            if dic[i] == 1:
                res.append(i)
            else:
                dic[i] -= 1
        
        return res


发表于 2022-02-24 21:45:09 回复(0)
import java.util.*;


public class Solution {
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public int[] removeDuplicate (int[] array) {
        // write code here
        int n = array.length;
        Set<Integer> set = new HashSet<>();
        int k = n-1;
        for(int i = n-1; i >=0; i--){
            if(!set.add(array[i]))continue;
            array[k--] = array[i];
        }
        return Arrays.copyOfRange(array, k+1, n);
    }
}

发表于 2024-09-17 11:08:22 回复(0)
public static Integer[] removeDuplication(int[] goal){

        Integer[] returnInt = {};

//        List<Integer> list = new ArrayList<>();
        List<Integer> list = new LinkedList<>();

        for (int i = 0; i < goal.length; i++) {
            list.add(goal[i]);
        }

        for (int i = 1; i < goal.length; i++) {
            for (int j = 0;j < i;j++){
                if (goal[i] == goal[j]) {
                    list.remove(list.indexOf(goal[j]));
                }
            }
        }

        returnInt = Arrays.copyOfRange(list.toArray(),0,list.size(),Integer[].class);

        return returnInt;
    }

发表于 2022-05-30 09:38:21 回复(0)
#
# 删除重复元素
# @param array int整型一维数组 
# @return int整型一维数组
#
class Solution:
    def removeDuplicate(self , array ):
        # write code here
        s=set()
        ret=[]
        array=array[::-1]
        for i in array:
            if i not in s:
                s.add(i)
                ret.append(i)
            else:
                pass
        return ret[::-1]   

发表于 2022-04-14 15:28:21 回复(0)
import java.util.*;


public class Solution {
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public int[] removeDuplicate (int[] array) {
        // write code here
        //直接从后往前遍历(放入栈中)
        int length = array.length;
        Stack<Integer> stack = new Stack<>();
        for (int i = array.length-1; i >= 0 ; i--) {
            if ( !stack.contains(array[i])){
                stack.push(array[i]);
            }
        }
        int[] res = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()){
            int cur = stack.pop();
            res[i++] = cur;
        }
        return res;
    }
}

// 超时了,栈的原因吗
发表于 2022-04-13 22:15:27 回复(0)
写个c艹版本
class Solution {
public:
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @param arrayLen int array数组长度
     * @return int整型vector
     */

    vector<int> removeDuplicate(int* array, int arrayLen) {
        vector<int> ans;
        unordered_set<int> set;
        for(int i = arrayLen - 1; i >= 0; i--)
        {
            if(set.find(array[i]) == set.end())
            {
                ans.push_back(array[i]);
                set.insert(array[i]);
            }
        }

        reverse(ans.begin(), ans.end());
        return ans;
    }
};


发表于 2022-03-18 14:51:03 回复(0)
//C++解法,使用哈希表
class Solution {
public:
    /**
     * 删除重复元素
     * @param array int整型一维数组 
     * @param arrayLen int array数组长度
     * @return int整型vector
     */
    vector<int> removeDuplicate(int* array, int arrayLen) {
        // write code here
        unordered_map<int,int>hp;
        vector<int> res;
        if(arrayLen==0) return res;
        
        else{
            for(int i=0;i<arrayLen;i++) hp[array[i]]=1;
        
            for(int i=arrayLen-1;i>=0;i--){
                if(hp[array[i]]==1){
                    res.push_back(array[i]);
                    hp[array[i]]=0;
            }
        }  
            reverse(res.begin(),res.end());
            }
        
        return res;
    }
};

编辑于 2022-03-16 22:05:54 回复(0)
public int[] removeDuplicate (int[] array) {

        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        for (int i = array.length-1; i >=0; i--) {
            set.add(array[i]);
        }
        int[] ints = new int[set.size()];
        int index=set.size()-1;
        for (Integer integer : set) {
            ints[index--]=integer;
        }       
        return ints;
}

编辑于 2022-03-09 14:47:25 回复(1)
#
# 删除重复元素
# @param array int整型一维数组 
# @return int整型一维数组
#
class Solution:
    def removeDuplicate(self , array ):
        # write code here
        c = set()
        i = len(array) - 1
        while i >= 0:
            if array[i] not in c:
                c.add(array[i])
            else:
                array.pop(i)
            i -= 1
        return array
            

发表于 2022-03-09 08:56:34 回复(0)
import java.util.*;


public class Solution {
    /**
     * 删除重复元素
     * @param array int整型一维数组 [3,5,8,2,3,8]
     * @return int整型一维数组
     */
    public int[] removeDuplicate (int[] array) {
        // write code here
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < array.length; i ++){
            map.put(array[i],i);
            //{3=0, 5=1, 8=2, 2=3}
            //{3=4, 5=1, 8=5, 2=3}
        }
        int[] res = new int[map.size()];
        int index = 0;
        for(int i = 0; i < array.length; i ++){
            if(map.get(array[i]) == i){
                res[index++] = array[i];
            }
        }
        return res;
    }
}
发表于 2022-02-26 21:06:37 回复(0)
反向遍历,用字典判断是否出现过
#
# 删除重复元素
# @param array int整型一维数组 
# @return int整型一维数组
#
class Solution:
    def removeDuplicate(self , array ):
        mp = {}
        ret = []
        for x in array[::-1]:
            if x in mp:
                continue
            else:
                mp[x] = 1
                ret.append(x)
        return ret[::-1]



发表于 2022-02-25 17:44:10 回复(0)
class Solution:
    def removeDuplicate(self , array ):
        # write code here
        for i in range(len(array)):
            if array[i] in array[i+1:]:
                array[i] = 0
        array1 = list(filter(lambda x:x!=0,array))
        return array1
发表于 2022-02-25 16:23:11 回复(0)
function removeDuplicate( array ) {
    // write code here
    let str = new Set()
    for(let i =0;i<array.length;i++){
        if(str.has(array[i])){
            str.delete(array[i])
        }
        str.add(array[i])
    }
    return [...str]
}
发表于 2022-02-21 15:32:03 回复(0)

问题信息

上传者:小小
难度:
19条回答 2317浏览

热门推荐

通过挑战的用户

删除数组中的重复项