📌  相关文章
📜  最后出现的数组元素(最后出现是最早的)

📅  最后修改于: 2021-10-28 01:36:47             🧑  作者: Mango

给定一个可能包含重复项的数组,找到最后一次出现的元素。
例子:

Input :  arr[] = {10, 30, 20, 10, 20}
Output : 30
Explanation: Below are indexes of last
appearances of all elements (0 based indexes)
10 last occurs at index 3
30 last occurs at index 1
20 last occurs at index 2
The element whose last appearance earliest
is 30.

Input : arr[] = {20, 10, 20, 20, 40, 10}
Output : 20
Explanation: 
Explanation: Below are indexes of last
appearances of all elements (0 based indexes)
20 last occurs at index 2
10 last occurs at index 5
40 last occurs at index 4
The element whose last appearance earliest
is 20.

一种天真的方法是获取每个元素并迭代并将其最后一次出现的元素与其他元素进行比较。这需要两个嵌套循环,并且需要 O(n*n) 时间。
一种有效的方法是使用散列。我们存储上次出现的每个元素的索引,然后遍历所有可能的元素并打印索引存储次数最少的元素,因为这将是从左到右遍历时最后看到的元素。

C++
// C++ program to find last seen element in
// an array.
#include 
using namespace std;
 
// Returns last seen element in arr[]
int lastSeenElement(int a[], int n)
{
    // Store last occurrence index of
    // every element
    unordered_map hash;
    for (int i = 0; i < n; i++)
        hash[a[i]] = i;
 
    // Find an element in hash with minimum
    // index value
    int res_ind = INT_MAX, res;
    for (auto x : hash)
    {
       if (x.second < res_ind)
       {
            res_ind = x.second;
            res = x.first;
       }
    }
 
    return res;
}
 
// driver program
int main()
{
    int a[] = { 2, 1, 2, 2, 4, 1 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << lastSeenElement(a, n);
    return 0;
}


Java
// Java program to find last seen element in
// an array.
import java.util.*;
 
class GFG
{
 
// Returns last seen element in arr[]
static int lastSeenElement(int a[], int n)
{
    // Store last occurrence index of
    // every element
    HashMap hash = new HashMap();
    for (int i = 0; i < n; i++)
    {
        hash.put(a[i], i);
    }
 
    // Find an element in hash with minimum
    // index value
    int res_ind = Integer.MAX_VALUE, res = 0;
    for (Map.Entry x : hash.entrySet())
    {
        if (x.getValue() < res_ind)
        {
            res_ind = x.getValue();
            res = x.getKey();
        }  
    }
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = { 2, 1, 2, 2, 4, 1 };
    int n = a.length;
    System.out.println(lastSeenElement(a, n));
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to find last seen
# element in an array.
import sys;
 
# Returns last seen element in arr[]
def lastSeenElement(a, n):
     
    # Store last occurrence index of
    # every element
    hash = {}
     
    for i in range(n):
        hash[a[i]] = i
         
    # Find an element in hash with minimum
    # index value
    res_ind = sys.maxsize
    res = 0
     
    for x, y in hash.items():
        if y < res_ind:
            res_ind = y
            res = x
             
    return res
 
# Driver code   
if __name__=="__main__":
     
    a = [ 2, 1, 2, 2, 4, 1 ]
    n = len(a)
     
    print(lastSeenElement(a,n))
 
# This code is contributed by rutvik_56


C#
// C# program to find last seen element in
// an array.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Returns last seen element in arr[]
static int lastSeenElement(int []a, int n)
{
    // Store last occurrence index of
    // every element
    Dictionary hash = new Dictionary();
    for (int i = 0; i < n; i++)
    {
        if(hash.ContainsKey(a[i]))
        {
            hash[a[i]] = i;
        }
        else
        {
            hash.Add(a[i], i);
        }
    }
 
    // Find an element in hash with minimum
    // index value
    int res_ind = int.MaxValue, res = 0;
    foreach(KeyValuePair x in hash)
    {
        if (x.Value < res_ind)
        {
            res_ind = x.Value;
            res = x.Key;
        }
    }
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = { 2, 1, 2, 2, 4, 1 };
    int n = a.Length;
    Console.WriteLine(lastSeenElement(a, n));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:

2

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程