您的位置:首页 > 其它

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

2014-08-10 17:38 495 查看
写完二分查找,变成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 search
			int low=0;
			int high=incantation1.size()-1;
			int mid=0;
			
			if(str.startsWith("[")){  //给出咒语查找对应功能 使用incantation1
				while(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{ //使用incantation2
				while(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?");
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: