Simple Java program using TreeSet, O(n) time


  • 0
    S
    public class Solution {
        public int thirdMax(int[] nums)  {
    	TreeSet<Integer> resultset= new TreeSet<Integer>(); 
    	for(int i=0;i<nums.length;i++){
    		resultset.add(nums[i]);
    		if(resultset.size()>3){
    			resultset.pollFirst();
    		}
    	}
    	return (resultset.size()<3)?resultset.pollLast():resultset.pollFirst();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.