Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/third-maximum-number/
- import java.util.TreeSet;
- /**
- * Using 3 variables.
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- */
- class Solution1 {
- public int thirdMax(int[] nums) throws IllegalArgumentException {
- if (nums == null || nums.length == 0) {
- throw new IllegalArgumentException("Invalid or Empty input nums array");
- }
- if (nums.length == 1) {
- return nums[0];
- }
- long max1 = Long.MIN_VALUE;
- long max2 = Long.MIN_VALUE;
- long max3 = Long.MIN_VALUE;
- for (int num : nums) {
- if (num == max1 || num == max2 || num == max3) {
- continue;
- }
- if (num > max1) {
- max3 = max2;
- max2 = max1;
- max1 = num;
- } else if (num > max2) {
- max3 = max2;
- max2 = num;
- } else if (num > max3) {
- max3 = num;
- }
- }
- return (int) (max3 == Long.MIN_VALUE ? max1 : max3);
- }
- }
- /**
- * Using TreeSet
- *
- * Time Complexity: O(N log N)
- *
- * Space Complexity: O(N)
- */
- class Solution2 {
- public int thirdMax(int[] nums) throws IllegalArgumentException {
- if (nums == null || nums.length == 0) {
- throw new IllegalArgumentException("Invalid or Empty input nums array");
- }
- TreeSet<Integer> set = new TreeSet<>();
- for (int num : nums) {
- set.add(num);
- if (set.size() > 3) {
- set.pollFirst();
- }
- }
- return set.size() == 3 ? set.first() : set.last();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement