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;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2219713