先排序后遍历
麻烦将问题描述详细一点哈
1234怎么算?算一次1234 还是 算两次123和234两种情况?
java实现如下:
import java.util.*; public class Tmp { public static void main(String[] args) { TimeProcess t = new TimeProcess(); // 进行赋值年-月-日, 要注意的是, 月份的范围为: 0-11, 表示1到12月 t.add(2009, 10, 4); t.add(2009, 10, 2); t.add(2009, 10, 3); t.add(2009, 11, 4); t.hasContinueThreeDays(); } } class TimeProcess { private ArrayList<GregorianCalendar> dateList; public TimeProcess() { dateList = new ArrayList<GregorianCalendar>(); } public void add(int year, int month, int day) { dateList.add(new GregorianCalendar(year, month-1, day)); } public boolean hasContinueThreeDays() { // 先进行排序 Collections.sort(dateList); // 至少需要三天 if (dateList.size() < 3) return false; long divid = 1000*24*3600; // 遍历判断 for (int i = 0; i < dateList.size() - 2; i++) { long first = dateList.get(i).getTimeInMillis()/divid; long second = dateList.get(i+1).getTimeInMillis()/divid; long third = dateList.get(i+2).getTimeInMillis()/divid; if (second - first == 1 && third - second == 1) { System.out.println("连续的三天为: "); System.out.println("\t" + dateList.get(i).getTime()); System.out.println("\t" + dateList.get(i+1).getTime()); System.out.println("\t" + dateList.get(i+2).getTime()); return true; } } System.out.println("没有连续的三天"); return false; } }
---------------------------------
希望对你有帮助。
用hash表维护,遍历一遍,对于每个时间判断相邻的另外两天在不在hash中(三种情况),如果在就是Yes,否则就是No