LeetCode irregular brush title --Peak Finder

Peak Finder

problem

Look for a peak in an array, so that it can be greater than his neighbors. Both ends of the array may be assumed to be negative infinity.

specific description

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

Algorithm Description

  1. Because we assume that both ends of the negative infinity, so long as we find the first element of the array is greater than the second or the last element is greater than the penultimate element to explain it to peak. If not found to use a for loop to traverse the array to determine whether an element is greater than its neighbor, you can find return. Complexity is O (n)
  2. Easy to prove in any sequence we can find a local peak, so we use dichotomy seek to determine the middle of the element is not, and if not, determine whether the elements of the middle element is greater than the right, it will be larger than the smaller sequence is a sequence of left ,vice versa. Complexity is O (logn)

Code

public static int traversal(int []numbers){
		if(numbers[0]>=numbers[1]){
			return numbers[0];
		}
		else if (numbers[numbers.length-1]>=numbers[numbers.length-2]){
			return numbers[numbers.length-1];
		}
		else{
		for(int i=1;i<numbers.length-1;i++){
			if(numbers[i-1]<=numbers[i]&&numbers[i+1]<=numbers[i]){
				return numbers[i];
			}
		}
		}
		return 0;
	}
public static int binarySearch(int []numbers){
		int low=0;
		int high=numbers.length-1;
		int mid=0;
		while(high>low){
			mid=(high+low)/2;
			if(numbers[mid]>=numbers[mid-1]&&numbers[mid]>=numbers[mid+1]){
				return numbers[mid];
			}
			else if(numbers[mid]>=numbers[mid+1]){
				high=mid;
			}
			else{
				low=mid+1;
			}
		}
		return low;
	}

Learn more about

Detailed answers to questions

Published 173 original articles · won praise 110 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_35564813/article/details/104723840