Java TreeSet O(n)


  • 0
    N

    class Solution {
    public int thirdMax(int[] nums) {
    TreeSet<Integer> c = new TreeSet<Integer>();
    int count = 0;
    int third = 0;
    for(int i=0;i<nums.length;i++){
    c.add(nums[i]);
    }
    if(c.size()<3){
    Arrays.sort(nums);
    return nums[nums.length-1];
    }
    Iterator<Integer> iterator = c.iterator();
    while(iterator.hasNext()){
    if((count+3)==c.size()) {
    third = iterator.next();
    break;
    }
    iterator.next();
    count++;
    }
    return third;
    }
    }


Log in to reply
 

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