forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindThreeLargest.java
More file actions
73 lines (63 loc) · 1.78 KB
/
FindThreeLargest.java
File metadata and controls
73 lines (63 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package algoexpert.easy;
/*
PROBLEM:
Return the three largest numbers in an array in sorted order
Input : int [] array
Output: int [] {three largest}
Solution:
1. Sort -> O(n logn) | space : O(1)
2. Three variables -> O(n) | space : O(1)
*/
import java.util.Arrays;
public class FindThreeLargest
{
// not part of problem
public static void printArray(int [] array)
{
System.out.print("[ ");
for (int x: array)
{System.out.print(x + " ");}
System.out.print("]");
System.out.println();
}
public static void test()
{
int[] testArr1 = {42, 82, 47};
int[] solution = sorter(testArr1);
printArray(solution);
}
// time: O(n logn) | space : O(1)
public static int[] sorter(int [] array)
{
Arrays.sort(array);
int largest = array[array.length -1];
int second = array[array.length -2];
int third = array[array.length -3];
return new int[] {third, second, largest};
}
// t : O(n) | s: O(1)
public static int[] findThreeLargestNumbers(int[] array)
{
int largest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
for(int i = 0; i < array.length; i++){
int current = array[i];
if (current > third){
if(current > second){
third = second;
if (current > largest){
second = largest;
largest = current;
}
else{ second = current; }
}
else{
third = current;
}
}
}
int [] solution = {third, second, largest};
return solution;
}
}