Problem of the Day
A new programming or logic puzzle every Mon-Fri

Top 3

Given an array of unsorted integers, return the largest 3 integers in the array. Can you solve this in linear runtime?

Permalink: http://problemotd.com/problem/top-3/

Comments:

  • mark - 10 years, 3 months ago

    var unsortedIntArray = new[] { 2, 3, 77, 33, 12, 75, 2, 9, 34, 59, 21, 17 };

    var top3 = unsortedIntArray.OrderByDescending(x => x).Take(3);

    reply permalink

  • wobblebucket - 10 years, 3 months ago

    def top(unsorted, num):
        r = []
        for x in range(num):
            top_idx = 0
            for idx, i in enumerate(unsorted):    
                if (i > unsorted[top_idx]):
                    top_idx = idx
    
            r.append(unsorted[top_idx])
            unsorted.pop(top_idx)
        return r
    
    print top([5,9,2,7,6,4,1,3,8], 3)
    

    reply permalink

  • asheehan - 10 years, 3 months ago

    in Ruby

    unsorted_array = 100.times.map{ Random.rand(100) }
    top_array = [0, 0, 0]
    unsorted_array.each do |x|
      for y in 0..2 do
        if top_array[y] < x
          top_array[y] = x
          top_array.sort!
          break
        end
      end
    end
    puts top_array
    

    reply permalink

  • person - 10 years, 3 months ago

    Erlang:

    -module(top3).
    -export([find_top3/1]).
    
    find_top3(L) ->
        find_top3(L, {0,0,0}).
    find_top3([], {Max, Med, Min})->
        {Max, Med, Min};
    find_top3([H|T], {Max, Med, Min}) when H >= Max ->
        find_top3(T, {H, Max, Med});
    find_top3([H|T], {Max, Med, Min}) when H =< Min ->
        find_top3(T, {Max, Med, Min});
    find_top3([H|T], {Max, Med, Min}) when H >= Med ->
        find_top3(T, {Max, H, Med});
    find_top3([H|T], {Max, Med, Min}) when H < Med ->
        find_top3(T, {Max, Med, H}).
    

    reply permalink

  • Foppe - 10 years, 3 months ago

    #! /usr/bin/python
    
    ints = [8, 445, 74, 85, 65, 90, 5, 102, 105, 558, 54, 2, 98, 26, 75]
    
    no1 = 0
    no2 = 0
    no3 = 0
    for i in ints:
        if i < no3:
            continue
        elif i > no1:
            no3 = no2
            no2 = no1
            no1 = i
            continue
        elif i > no2:
            no3 = no2
            no2 = i
            continue
        else:
            no3 = i
    
    print("%d %d %d" % (no1, no2, no3))
    

    reply permalink

Content curated by @MaxBurstein