852 Peak Index in a Mountain Array
Let's call an array A
a mountain if the following properties hold:
A.length >= 3
- There exists some
0 < i < A.length - 1
such thatA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i
such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
.
public static int mountainarray_852(int[] a) {
int n = a.length;
int low = 0;
int high = n-1;
int mid=0;
if(n == 1) return a[1];
if( n ==2 ) return a[n-1];
while(low < high){
mid = low + (high-low)/2;
if(a[mid] < a[mid+1]){
low = mid;
} else if (a[mid] < a[mid-1]){
high = mid;
}else return mid;
}
return 0;
}
很简单的二分搜索法,没什么好讲的,或者你也可以直接for循环a[i]>a[i-1]就可以,主要是为了复习下二分定义。
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.