`

Google Interview - Second Largest Number

 
阅读更多

Find the second largest number in a given array.
Return 0 if the given array has no second largest number.

 

public int secondLargest(int[] arr) {
    if(arr.length<2) return 0;
    int first = Math.max(arr[0], arr[1]);
    int second = Math.min(arr[0], arr[1]);
    for(int i=2; i<arr.length; i++) {
        if(arr[i] > first) {
            second = first;
            first = arr[i];
        } else if(arr[i] > second && arr[i] < first) {
            second = arr[i];
        }
    }
    if(first == second) return 0;
    return second;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics