判断不同的起始坐标袋鼠在经历过多少次起跳之后是否可以达到相同的终点
package com.hackerRank; import java.util.ArrayList; import java.util.List; import java.util.Random; public class HackerRankTest { public static void main(String[] args) { System.out.println("Hello world!"); String kangaroo = kangaroo(0,3,4,2); System.out.println(kangaroo); } /** * 判断不同的起始坐标袋鼠在经历过多少次起跳之后是否可以达到相同的终点 * 坐标是x轴的坐标,起跳单元是x轴单元坐标的倍数 * 约束 * 0<=x1<x2<=10000 * 1<=v1<=10000 * 1<=v2<=10000 * @param x1 * @param v1 * @param x2 * @param v2 * @return */ public static String kangaroo(int x1,int v1,int x2,int v2) { if(x1<0 || x1>10000) { return "NO"; } if(x2<0 || x2>10000) { return "NO"; } if(x1>x2) { return "NO"; } if(v1<1 || v1>10000) { return "NO"; } if(v2<1 || v2>10000) { return "NO"; } int kangarooNO1Step=0; int kangarooNO1Dest=x1; ArrayList<Integer> arrayList = new ArrayList<Integer>(); int count=0; while(true) { for (int i = 0; i < kangarooNO1Step; i++) { kangarooNO1Dest+=(kangarooNO1Step*v1); arrayList.add(kangarooNO1Dest); kangarooNO1Step++; if(kangarooNO1Step<10000) { continue; } } if(count>1000000) { break; } count++; } int kangarooNO2Step=0; int kangarooNO2Dest=x2; List<Integer> arrayList2=new ArrayList<Integer>(); int count1=0; while(true) { for (int i = 0; i < kangarooNO2Step; i++) { kangarooNO2Dest+=(kangarooNO2Step*v2); arrayList2.add(kangarooNO2Dest); kangarooNO2Step++; if(kangarooNO2Step<10000) { continue; } } if(count1>1000000) { break; } count1++; } int count2=0; Random random = new Random(); while(true) { int nextInt = random.nextInt(arrayList.size()); Integer integer = arrayList.get(nextInt); int nextInt2=random.nextInt(arrayList2.size()); Integer integer2 = arrayList.get(nextInt2); if(nextInt==integer2) { return "YES"; } if(count2>1000000) { break; } count2++; } return "NO"; } }
Java技术 文章被收录于专栏
JavaEE技术 编程开发经验 企业通用技术