【九度OJ】1029【二分查找】

来源:互联网 发布:北京婚纱照外景 知乎 编辑:程序博客网 时间:2024/05/16 09:38

写完二分查找,变成600MS了。。。300MS的到底怎么写的。。。

代码:

package Test1;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Scanner;public class Test10_2_1029 {/** * by qr jobdu 1029 2014-8-10 */public static void main(String[] args) {Scanner scan = new Scanner(System.in);List<String> incantation1=new ArrayList<String>();  //咒语在前,功能在后List<String> incantation2=new ArrayList<String>();  //功能在前,咒语在后String str = scan.nextLine();while (!str.equals("@END@")) {incantation1.add(str);str=str.substring(str.indexOf("]") + 2)+" "+str.substring(0, str.indexOf("]") + 1);incantation2.add(str);str = scan.nextLine();}Collections.sort(incantation1);Collections.sort(incantation2);int n =Integer.parseInt(scan.nextLine());  for (int i = 0; i < n; i++) {str = scan.nextLine();  //binary searchint low=0;int high=incantation1.size()-1;int mid=0;if(str.startsWith("[")){  //给出咒语查找对应功能 使用incantation1while(low<=high){mid=(low+high)/2;String s=incantation1.get(mid);s=s.substring(0,s.indexOf("]")+1);if(s.compareTo(str)>0){high=mid-1;}else if(s.compareTo(str)<0){low=mid+1;}else{str=incantation1.get(mid);System.out.println(str.substring(str.indexOf("]")+2));break;}}}else{ //使用incantation2while(low<=high){mid=(low+high)/2;String s=incantation2.get(mid);s=s.substring(0,s.indexOf("[")-1);if(s.compareTo(str)>0){high=mid-1;}else if(s.compareTo(str)<0){low=mid+1;}else{str=incantation2.get(mid);System.out.println(str.substring(str.indexOf("[")+1,str.indexOf("]")));break;}}}if(low>high)System.out.println("what?");}}}


0 0
原创粉丝点击