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

写完二分查找,变成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?");
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值