【每日一题0914】从左去重

:woman_mage:给定一个由正整数组成的列表nums,请编写一个函数,若某个元素出现重复,则将其左侧相同值的元素都移除,并返回余下的列表。

示例:
输入:[3,4,4,3,6,3],输出:[4,6,3]
说明:首先索引0和3的元素3会被去除,然后索引1的元素4会被去除。

题目难度:简单
题目来源:codewars

# Python
def remove_left(nums: int) -> list:
    pass

assert remove_left([3,4,4,3,6,3]) == [4,6,3]
assert remove_left([1,2,1,2,1,2,3]) == [1,2,3]
assert remove_left([1,2,3,4]) == [1,2,3,4]
// Java
public int[] removeLeft(int[] nums) {
    
}

assertEquals(removeLeft([3,4,4,3,6,3]),[4,6,3])
assertEquals(remove_left([1,2,1,2,1,2,3]),[1,2,3])
assertEquals(remove_left([1,2,3,4]),[1,2,3,4])
# 一解 反转列表
def remove_left(nums):
    list1=[]
    newlist=list(reversed(nums))
    print(newlist)
    for i in newlist:
        if i not in list1:
            list1.append(i)
    list2=list(reversed(list1))
    return list2
# 二解 根据索引 写的有点复杂,没用一些方法
def remove_left1(nums):
    list1=list(set(nums))
    # 存放索引
    list2=[]
    # 存放最后的值
    list3=[]
    dictionary=dict.fromkeys(list1)
    for i in range(len(nums)):
        dictionary[nums[i]]=i
    print(dictionary)
    for key,value in dictionary.items():
        list2.append(value)
    list2=sorted(list2)
    for i in list2:
        list3.append(nums[i])
    print(list3)
    return list3
public ArrayList<Integer> removeLeft(ArrayList<Integer> nums) {
        for (int i = nums.size()-1; i >0; i--) {
            for (int j = i-1; j >= 0; j--) {
                if (nums.get(i) == nums.get(j)) {
                    nums.remove(j);
                    break;
                }
            }
        }
        return nums;
    }

    @Test
    public void testRemoveLeft() {
        ArrayList<Integer> a = new ArrayList<>();
        a.addAll(Arrays.asList(3,4,4,3,6,3));
        assertEquals(removeLeft(a), Arrays.asList(4, 6, 3));
        ArrayList<Integer> a1 = new ArrayList<>();
        a1.addAll(Arrays.asList(1,2,1,2,1,2,3));
        assertEquals(removeLeft(a1), Arrays.asList(1,2,3));
        ArrayList<Integer> a2 = new ArrayList<>();
        a2.addAll(Arrays.asList(1,2,3,4));
        assertEquals(removeLeft(a2), Arrays.asList(1,2,3,4));
    }
def remove_left(nums):
    for i in nums:
        while nums.count(i)>1:
            nums.remove(i)
    return nums

# 思路:利用remove函数移除列表中的第一个匹配项
关闭