Accepted solution by Java, in 344ms


  • 0
    A
    public class Solution {
    public void insert_num(int[] my_array, int to_insert, int index){
    	if(index == my_array.length-1){
    		my_array[index] = to_insert;
    	}else if(my_array.length >= 2){
    		int i = 0;
    		for(i=my_array.length-1;i>index;i--){
    		my_array[i]=my_array[i-1];
    		}
    		my_array[i+1] = my_array[i];
    		my_array[i] = to_insert;
    	}
    }
    
    public int findKthLargest(int[] nums, int k) {
        int[] my_array = new int[k];
    	boolean empty_flag = true;
        int end_index = 0;
    	
    	if(nums.length < k){
    		return 0;
    	}
    	if(nums.length == 0){
    		return 0;
    	}
    	if(nums.length == 1){
    		return nums[0];
    	}
    	
    	for(int i=0;i<nums.length;i++){
    		if(empty_flag == true){
    			my_array[end_index]=nums[i];
    			empty_flag = false;
    			continue;
    		}
    		if(end_index < k-1){
    			for(int j=0;j<=end_index;j++){
    				if(j != end_index){
    					if(my_array[j] > nums[i]){
    						continue;
    					}else{
    						insert_num(my_array, nums[i], j);
    						end_index++;
    					}
    				}else if(j == end_index){
    					if(nums[i] > my_array[j]){
    						insert_num(my_array, nums[i], j);
    						end_index++;
    					}else{
    						insert_num(my_array, nums[i], j+1);
    						end_index++;
    					}
    				}
    				break;
    			}
    		}else if(nums[i] >= my_array[end_index]){
    			for(int j=0;j<=end_index;j++){
    				if(nums[i] >= my_array[j]){
    					insert_num(my_array, nums[i], j);
    					break;
    				}
    			}
    		}
    	}
    	return my_array[k-1];
    }
    

    }

    No libs used. Tried to reduce loops which wastes time with IFs.

    Well, maybe I should use C instead... Using linked list or something.

    This code creates an int array "my_array" with length "k".

    While traversing array "nums", it first fills array "my_array" ascend.

    After "my_array" is full, if "nums[i]" is bigger than or equal to the last(while, smallest) element, it will be inserted after the last one in "my_array" which is bigger than "nums[i]", or be the top of "my_array" if there is not a bigger element.

    And when finished traversing array "nums", the last element in "my_array" will be the result.


Log in to reply
 

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