JAVA手撕二分查找
查找
http://www.nowcoder.com/questionTerminal/d93db01c2ee44e8a9237d63842aca8aa
前半段是用两个辅助数组存值
后半段二分查找,找到后break返回,设置flag锁来定输出
注意这里while()循环条件是left<right
以及转移时是left=mid+1; .... right=mid;
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { int[] temp; int[] num; Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int n=sc.nextInt(); temp=new int[n]; for(int i=0;i<n;i++){ temp[i]=sc.nextInt(); } Arrays.sort(temp); int m=sc.nextInt(); num=new int[m]; for(int i=0;i<m;i++){ num[i]=sc.nextInt(); } for(int i=0;i<m;i++){ binSearch(temp,num[i],n); } } } public static void binSearch(int[] A,int target,int n){ int left=0,right=n; int flag=0; while(left<right){ int mid=(left+right)/2; if(A[mid]<target){ flag=0; left=mid+1; }else if(A[mid]>target){ flag=0; right=mid; }else{ flag=1; break; } } if(flag==1){ System.out.println("YES"); }else{ System.out.println("NO"); } } }