赛码网OJ题目--股神

 

1. 题目描述

 

2. 第一版

 

import java.util.Scanner;

public class 股神 {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		int day;
		while (scanner.hasNext()) {
			day = scanner.nextInt();
			long time1 = System.currentTimeMillis();
			System.out.println(getMoney(day));
			long time2 = System.currentTimeMillis();
			System.out.println(time2-time1);
		}
		
	}
	
	public static int getMoney(int day){
		int total = 0;
		for (int i = 1; i <= day; i++) {
			if(isIncr(i)){
				total++;
			}else{
				total--;
			}
		}
		return total;
	}
	
	public static boolean isIncr(int day){
		int interval = 3;
		int temp = 3;
		while (temp<day) {
			temp += interval++;
		}
		if(temp==day){
			return false;
		}else{
			return true;
		}
	}

}

 

结果发现:

Time Limit Exceeded

TLE

您的程序运行的时间已经超出了题目的时间限制。

问题就出在每个数字都要进行判断

比如10000000  结果是9991060  而所需时间是20467ms  20多秒才能计算出来

 

3. 第二版

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		int day;
		while (scanner.hasNext()) {
			day = scanner.nextInt();
			long time1 = System.currentTimeMillis();
			System.out.println(getMoney(day));
			long time2 = System.currentTimeMillis();
			System.out.println(time2-time1);
		}
	}

	public static int getMoney(int day) {
		
		if(day==1){
			return 1;
		}else{
			
			int curr = 1;
			int cycleNum = 1;
			int total = 1;
			
			while (curr < day) {
				// 执行一个循环
				{
					// 第一个循环是 第二天 第三天
					// 第二个循环是 第四天 第五天 第六天...
					for (int i = 0; i < cycleNum; i++) {
						total++;
						curr++;
						if (curr == day) {
							return total;
						}
					}
					// 完成循环的最后一步
					total--;
					curr++;
				}
				if (curr == day) {
					return total;
				}
				cycleNum++;
			}
			return total;
		}
	}

}

比如10000000  结果是9991060  而所需时间是7ms

4. 总结

算法优化是多么明显地带来计算效率的提升!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值