Given an array of integers, find the first integer that is unique

Given an array of integers, find the first integer that is unique.

my solution: use std::map

put an integer (number as a key, its index as a value) to it one after another (O(n^2 lgn)), if it has a duplicate, delete the record from the card (O(lg n)), after putting all the numbers in the card, iterating the card and find the key with the lowest index O (n).

O(n^2 lgn)because the card must do the sorting.

It is inefficient.

other better solutions?

+3
source share
6 answers

, , , /:

1: -, , . O (n), / - . , ( ).

2: . , - , (.. ). O (n), O (n).

:

A: , -. O (1) , . , , . - (.. - ). , -- -, (.. ).

( 255) , . , (.. ) , . , .

, 64- , 4 , 32- . .

, minmax .

B: . , 2 ( , ). , . , , .

+11

. 2 for-loops, O(n^2) algo.

-, , @Micheal Goldshteyn

: , 1 . , , . , , -.

, . : [5, 5, 66, 66, 7, 1, 1, 77]. 3. (5,5,66). . . 1 , (5,66,66). . (66,66,7). . (66,7,1). ! , . , 1. , 7 - .

: O (1) : O (n) * O (m ^ 2) = O (n) * 9 ≈ O (n)

+1

O(log n) not O(n log n), n n log n. set.

0
source

Although O (n ^ 2) has small coefficients, it’s not so bad in the cache and uses memmem()which is fast.

 for(int x=0;x<len-1;x++)
     if(memmem(&array[x+1], sizeof(int)*(len-(x+1)), array[x], sizeof(int))==NULL &&
        memmem(&array[x+1], sizeof(int)*(x-1), array[x], sizeof(int))==NULL)
            return array[x];
0
source
public static string firstUnique(int[] input)  
{
    int size = input.Length;
    bool[] dupIndex = new bool[size];
    for (int i = 0; i < size; ++i) 
    {
        if (dupIndex[i]) 
        {
            continue;
        } 
        else if (i == size - 1) 
        {
            return input[i].ToString();
        }
        for (int j = i + 1; j < size; ++j) 
        {
            if (input[i]==input[j]) 
            {
                dupIndex[j] = true;
                break;
            } 
            else if (j == size - 1)
            {
                return input[i].ToString();
            }
        }
    }
    return "No unique element";
}
0
source

@ user3612419

  Solution given you is good with some what close to O(N*N2) but further optimization in same code is possible I just added two-3 lines that you missed.



public static string firstUnique(int[] input)  
{
  int size = input.Length;
  bool[] dupIndex = new bool[size];
  for (int i = 0; i < size; ++i) 
  {
     if (dupIndex[i]) 
    {
        continue;
    } 
    else if (i == size - 1) 
    {
        return input[i].ToString();
    }
    for (int j = i + 1; j < size; ++j) 
    {
  if(dupIndex[j]==true)
  {
 continue;
 }
        if (input[i]==input[j]) 
        {
            dupIndex[j] = true;
    dupIndex[i] = true;
            break;
        } 
        else if (j == size - 1)
        {
            return input[i].ToString();
         }
     } 
  }
return "No unique element";
 }
0
source

Source: https://habr.com/ru/post/1606961/


All Articles