Defines the concept of a local minimum. Arr has a length of 1 o'clock, arr[0] is the local smallest. If Arr has a length of N (n>1), if arr[0]<arr[1], then arr[0] is the local minimum; if arr[n-1]<arr[n-2], then arr[n-1] is the local smallest; if 0<i<n-1, Both arr[i]<arr[i-1] and arr[i]<arr[i+1], then Arr[i] is the local smallest. Given an unordered array of arr, it is known that any two contiguous numbers in Arr are unequal, write a function, and simply return to any of the local smallest occurrences in arr.
public class Solution {public static int findpartmin (int[] data,int lo,int hi) {while (Lo<=hi) { int mid = L o+ (Hi-lo)/2; if (data[mid]<data[mid-1]&&data[mid]<data[mid+1]) return mid; else if (data[mid]>data[mid-1]) hi = mid-1; else if (data[mid]>data[mid+1]) lo = mid+1; } return-1; } public int getlessindex (int[] arr) { if (arr.length==1) return 0; else if (arr.length>1) { if (arr[0]<arr[1]) return 0; else if (Arr[arr.length-1]<arr[arr.length-2]) return arr.length-1; else return findpartmin (arr,1,arr.length-2); } else return-1;} }
For an ordered array of arr, given an integer num, find the leftmost position in arr where Num appears.
Given an array of arr and its size n, given numat the same time. Please return to the location you are seeking. If the element does not appear in the array, return-1.
Test examples:
[1,2,3,3,4],5,3
Returns: 2
Import java.util.*;p Ublic class Leftmostappearance {public int findpos (int[] arr, int n, int num) { //write code Here int left = 0,right = n-1; int pos =-1; while (left<=right) { int mid = left+ (right-left)/2; if (arr[mid]>num) Right = mid-1; else if (arr[mid]<num) left = mid+1; else{ pos = mid; right = Mid-1; } } return pos; }}
There is an ordered array of arr, which does not contain duplicate elements, find the leftmost position that satisfies the arr[i]==i condition. Returns 1 if the number on all positions does not meet the criteria.
Given an ordered array of arr and its size n, return the evaluated value.
Test examples:
[ -1,0,2,3],4
Returns: 2
Import java.util.*;p Ublic class Find {public int findpos (int[] arr, int n) { //write code here int left = 0, right = n-1; while (left<=right) { int mid = left+ (right-left)/2; if (arr[left]==left) return left; if (arr[mid]>mid) Right = mid-1; else if (arr[mid]<mid) left = mid+1; else return mid; } return-1;} }
Two-point Search