The general solution of the problem to find Kth number !!


  • 0
    Z

    public class Solution {

    public int thirdMax(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int num:nums)
            set.add(num);
        int[] nums1 = new int[set.size()];
        int k=0;
        for(int s:set)
            nums1[k++] = s;
        if(nums1.length==1) return nums1[0];
        if(nums1.length==2) return Math.max(nums1[0],nums1[1]);
        return helper(nums1,0,nums1.length-1,nums1.length-3);
    }
    
    private int helper(int[] nums,int start,int end,int target){
        int i=start,j=end,value = nums[start];
        while(i<j){
            while(i<j&&nums[j]>=value) j--;
            nums[i] = nums[j];
            while(i<j&&nums[i]<value) i++;
            nums[j]=nums[i];
        }
        nums[j] = value;
        if(j==target) return nums[j];
        else if(j>target) return helper(nums,start,j-1,target);
        else return helper(nums,j+1,end,target);
    }
    

    }


Log in to reply
 

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