Finding first non-repeating number in integer array

后端 未结 4 1753
天涯浪人
天涯浪人 2021-02-20 03:55

I got this question for an exam:

Given an integer array find the first number which is not repeating in array using O(N) time complexity and O(1) space co

4条回答
  •  暖寄归人
    2021-02-20 04:15

    I did this using PowerShell

    [int[]]$arr = @(6,2,1,2,6,1,7)
    
    $Collection = New-Object 'System.Collections.Generic.list[System.Object]'
    $props=[ordered]@{"Index"=9999;"Value"=9999;"Numcount"=9999}
    $record = New-Object -TypeName psobject -Property $props
    $Collection.Add($record) #This record is added to do a Contains operation 
    #for future items to be added in the $collection object
    
    for($i =0;$i -lt $arr.Length;$i++)
    {
    if($i -eq 0)
    {
        $props=[ordered]@{"Index"=$i;"Value"=$arr[$i];"Numcount"=1}
        $record = New-Object -TypeName psobject -Property $props
        $Collection.Add($record)
    }
    
    
    elseif($Collection.value.Contains($arr[$i]))
    {
    
        $count = ($Collection | ?{$_.Value -eq $arr[$i]} | select -First `
    1).Numcount
        ($Collection | ?{$_.Value -eq $arr[$i]} | select -First 1).Numcount = `
    $count+1
    }
    else
    {
        $props=[ordered]@{"Index"=$i;"Value"=$arr[$i];"Numcount"= 1}
        $record = New-Object -TypeName psobject -Property $props
        $Collection.Add($record)
    }
    
    }
    Write-Output "The first non repeating number in the array is listed below"
    $Collection | Sort-Object Numcount -Descending | ?{$_.Numcount -eq 1} | 
    Select -First 1
    
    OUTPUT:-
    The first non repeating number in the array is listed below
    Index Value Numcount
    ----- ----- --------
    6     7        1
    

提交回复
热议问题