Skip to content

Commit ce32b0f

Browse files
third max number
1 parent 426caa6 commit ce32b0f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

‎EASY/src/easy/ThirdMaximumNumber.java

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package easy;
2+
3+
public class ThirdMaximumNumber {
4+
5+
public static int thirdMax_20161115(int[] nums) {
6+
7+
if (nums == null || nums.length == 0) return 0;
8+
if (nums.length < 3) {
9+
int max = 0;
10+
for (int i : nums) {
11+
max = Math.max(i, max);
12+
}
13+
return max;
14+
}
15+
16+
long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
17+
18+
for (int i = 0; i < nums.length; i++){
19+
if (nums[i] > first) {
20+
long tmpFirst = first;
21+
first = nums[i];
22+
23+
long tmpSecond = second;
24+
second = tmpFirst;
25+
26+
third = tmpSecond;
27+
} else if (nums[i] == first) continue;
28+
else if (nums[i] > second) {
29+
long tmpSecond = second;
30+
second = nums[i];
31+
32+
third = tmpSecond;
33+
} else if (nums[i] == second) continue;
34+
else if (nums[i] > third) {
35+
third = nums[i];
36+
}
37+
}
38+
39+
if (third == Long.MIN_VALUE){
40+
return (int) first;
41+
}
42+
43+
return (int) third;
44+
45+
}
46+
47+
public static void main(String...strings){
48+
// int[] nums = new int[]{1,2};
49+
// int[] nums = new int[]{2,2,3,1};
50+
// int[] nums = new int[]{1,1,2};//should be 2
51+
int[] nums = new int[]{1,2,-2147483648};//should be -2147483648
52+
// int[] nums = new int[]{3,2,1};
53+
// System.out.println(thirdMax(nums));
54+
System.out.println(thirdMax_20161115(nums));
55+
}
56+
57+
}

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
|419|[Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/)|[Solution](../../blob/master/MEDIUM/src/medium/BattleshipsinaBoard.java) | O(n^2) |O(1) | Medium| DFS
1313
|417|[Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)|[Solution](../../blob/master/MEDIUM/src/medium/PacificAtlanticWaterFlow.java) | O(m*n*Max(m,n)) |O(m*n) | Medium| DFS
1414
|415|[Add Strings](https://leetcode.com/problems/add-strings/)|[Solution](../../blob/master/EASY/src/easy/AddStrings.java)| O(n)|O(1) | Easy|
15+
|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/)|[Solution](../../blob/master/EASY/src/easy/ThirdMaximumNumber.java)| O(n)|O(1) | Easy|
1516
|413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/)|[Solution](../../blob/master/MEDIUM/src/medium/ArithmeticSlices.java) | O(n) |O(1) | Medium| DP
1617
|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)|[Solution](../../blob/master/EASY/src/easy/FizzBuzz.java)| O(n)|O(1) | Easy|
1718
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/)|[Solution](../../blob/master/EASY/src/easy/SumofLeftLeaves.java)| O(n)|O(h) | Easy|

0 commit comments

Comments
 (0)