只记得大致的内容:
      比如输入一个时间“12:18”   在给定String数组里面找到离这个时间最接近的时间,并输出
   给定数组里面的值大致是这样的{“01:16”,“06:22”“14:54”“13:35”“12:19”“12:20”  }       C或者java都行    看各位有什么较好的解决方法没
       

解决方案 »

  1.   

    每个取出toTime下 然后排序
      

  2.   

    这题给我,我看只能挨个拆分数组中的字符串,然后转化成int型,再给个新数组赋值,然后比较大小吧
      

  3.   

    话说,直接用Arrays.sort()不行么?
      

  4.   


    package com.ss;import java.util.Arrays;
    import java.util.Comparator;public class TimeSort
    {
    public static void main(String[] args)
    {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20" };
    HM[] hms = new HM[hmstr.length + 1];
    for (int i = 0; i < hmstr.length; i++)
    {
    hms[i] = new HM(hmstr[i]);
    }
    String hm = "12:18";
    HM now = new HM(hm);
    hms[hmstr.length] = now;
    Arrays.sort(hms);
    int index = 0;
    for (int j = 0; j < hms.length; j++)
    {
    if (hms[j].toString().equals(hm))
    {
    index = j;
    break;
    }
    }
    if (index > 0)
    {
    HM hm1 = hms[index - 1];
    HM hm2 = hms[index + 1];
    if(hm2.minus(now)>now.minus(hm1))
    {
    System.out.println("最接近的时间是:" + hm1);
    }
    else
    {
    System.out.println("最接近的时间是:" + hm2);
    }
    } else
    {
    System.out.println("最接近的时间是:" + hms[index + 1]);
    } }
    }class TimeComparator implements Comparator<HM>
    {
    public int compare(HM hm1, HM hm2)
    {
    if (hm1 == null || hm2 == null)
    {
    return 0;
    }
    return hm1.minus(hm2);
    }
    }class HM implements Comparable<HM>
    {
    int hour;
    int minute; HM(String s)
    {
    if (s.indexOf(":") > 0)
    {
    String[] hm = s.split(":");
    hour = Integer.parseInt(hm[0]);
    minute = Integer.parseInt(hm[1]);
    }
    } public int compareTo(HM o)
    {
    return minus(o);
    } public String toString()
    {
    return this.hour + ":" + this.minute;
    } public int minus(HM o)
    {
    if (o == null)
    {
    return this.hour * 60 + this.minute;
    } else
    {
    return (this.hour - o.hour) * 60 + (this.minute - o.minute);
    }
    }
    }
      

  5.   


    package com.lzz.datetest;
    import java.util.Date;
    public class DateTest1 { /**
     * @param args
     */
    public static void main(String[] args) {

    //compareDateTime();
    ceshi();
    } public static void ceshi(){
    String s="12:18";
    String[] ss={"12:28","13:37","12:21","18:30","12:20"};
    int k=0;
    int[] ii=new int[ss.length];
    for(int i=0;i<ii.length;i++){
    ii[i]=compareOne(stringtoTime(s), stringtoTime(ss[i]));
    System.out.println("第"+i+"个时间差是:"+ii[i]);
    }

    //比较出差值最小的那个时间在String数组中的下标
    for(int j=0;j<ii.length-1;j++){
    if(ii[j]<ii[j+1]){
    //System.out.println("时间差最小的是第"+j+"个");
    k=j;
    }else{
    //System.out.println("时间差最小的是第"+(j+1)+"个");
    k=j+1;
    }

    }
    System.out.println("和规定时间差距最小的是:"+ss[k]);
    }

    //把一个String的时间变成Date类型
    public static Date stringtoTime(String s){
    int i=0;
    int j=0;
    String[] ss=s.split(":");
    //System.out.println(ss[0]+":"+ss[1]);
    i=Integer.parseInt(ss[0]);
    j=Integer.parseInt(ss[1]);
    Date d=new Date(0, 0, 0, i, j, 0);
    //System.out.println(d);
    return d;
    }

    //得到2个时间的差值
    public static int compareOne(Date d1,Date d2){
    long i=d1.getTime()-d2.getTime();
    long j=Math.abs(i);
    //System.out.println(j);
    return (int)j;
    }
    }
      

  6.   

    我的做法,我就把数组的值全部转化为float值。然后进行排序。然后进行查找。
      

  7.   

    o(n)的时间复杂度就可以完成。没必要用O(N2)
      

  8.   

    import java.util.ArrayList;
    import java.util.List;public class Test{
    public static void main(String args[]) {
    String s = "12:18";
    String[] ss = { "12:28", "13:37", "12:16", "18:30", "12:20" };
    int compareData = getInteger(s);
    List<String> result = new ArrayList<String>();
    int minDistance = Integer.MAX_VALUE;
    for (String tempStr : ss) {
    int tempdata = Math.abs(compareData - getInteger(tempStr));
    System.out.println(tempdata);
    if (minDistance > tempdata) {
    result.clear();
    result.add(tempStr);
    minDistance = tempdata;
    } else if (minDistance == tempdata) {
    result.add(tempStr);
    }
    }
    System.out.println(result);
    } public static int getInteger(String s) {
    String temp[] = s.split(":");
    int data = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
    return data;
    }
    }
      

  9.   

    import java.util.ArrayList;
    import java.util.List;public class Test{
    public static void main(String args[]) {
    String s = "12:18";
    String[] ss = { "12:28", "13:37", "12:16", "18:30", "12:20" };
    int compareData = getInteger(s);
    List<String> result = new ArrayList<String>();
    int minDistance = Integer.MAX_VALUE;
    for (String tempStr : ss) {
    int tempdata = Math.abs(compareData - getInteger(tempStr));
    System.out.println(tempdata);
    if (minDistance > tempdata) {
    result.clear();
    result.add(tempStr);
    minDistance = tempdata;
    } else if (minDistance == tempdata) {
    result.add(tempStr);
    }
    }
    System.out.println(result);
    } public static int getInteger(String s) {
    String temp[] = s.split(":");
    int data = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
    return data;
    }
    }
      

  10.   


    import java.util.ArrayList;
    import java.util.List;public class Test {
    public static void main(String args[]) {
    String s = "12:18";
    String[] ss = { "12:28", "13:37", "12:16", "18:30", "12:20" };
    int compareData = getInteger(s);
    List<String> result = new ArrayList<String>();
    int minDistance = Integer.MAX_VALUE;
    for (String tempStr : ss) {
    int tempdata = Math.abs(compareData - getInteger(tempStr));
    System.out.println(tempdata);
    if (minDistance > tempdata) {
    result.clear();
    result.add(tempStr);
    minDistance = tempdata;
    } else if (minDistance == tempdata) {
    result.add(tempStr);
    }
    }
    System.out.println(result);
    } public static int getInteger(String s) {
    String temp[] = s.split(":");
    int data = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
    return data;
    }
    }
      

  11.   

    public class FindTime {static int getTime(String timestr1,String timestr2){

    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {

         return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
    public static void main(String[] args) {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
      

  12.   

    [code = java code]
    public class FindTime {static int getTime(String timestr1,String timestr2){

    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {

         return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
    public static void main(String[] args) {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
    [/code]
      

  13.   

    [code = java code]
    public class FindTime {
    static int getTime(String timestr1,String timestr2){
    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {
              return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
        public static void main(String[] args) {
       String[] hmstr =  {"01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
    [/code]
      

  14.   

    [code = java code]
    public class FindTime {static int getTime(String timestr1,String timestr2){

    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {

         return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
    public static void main(String[] args) {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
    [/code]
      

  15.   

    [code = java code]
    public class FindTime {static int getTime(String timestr1,String timestr2){

    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {

         return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
    public static void main(String[] args) {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:17", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
    [/code]
      

  16.   

    将时间全部转成秒,以00:00为0秒,与要比较的时间相减取绝对值 over
      

  17.   

    将时间全部转成秒,以00:00为0秒,与要比较的时间相减取绝对值 over
      

  18.   

    将时间全部转成秒,以00:00为0秒,与要比较的时间相减取绝对值 over
      

  19.   

    转换为分钟,然后比较分钟的差的绝对值。a:b代表的分钟是60*a+b
      

  20.   

    [code = java code]
    public class FindTime {static int getTime(String timestr1,String timestr2){

    String[]  str1 = timestr1.split(":");
    String[]  str2 = timestr2.split(":");
    try {

         return Math.abs(Integer.parseInt(str1[0])*60 +Integer.parseInt(str1[1])
                -Integer.parseInt(str2[0])*60 - Integer.parseInt(str2[1]));
    } catch (Exception e) {
        return  -1 ;
    }
    }
    public static void main(String[] args) {
    String[] hmstr = { "01:16", "06:22", "14:54", "13:35","12:18", "12:19", "12:20" };
    int min = 1000000;
    int a = 0;
    String timeString = "";
    for(String stime :hmstr){
    a = getTime(stime,"12:18");
    if ( a < min ){
    min = a;
    timeString = stime;
    }
    }
    if ( a != -1){
    System.out.println(timeString);
    }    
    else {
    System.err.println("出错!");
    }
    }}
    [/code]
      

  21.   

    发了2个帖子都被吞了,心寒。鼓起勇气发第三遍。import java.util.ArrayList;
    import java.util.List;public class Test {
    public static void main(String args[]) {
    String s = "12:18";
    String[] ss = { "12:28", "13:37", "12:16", "18:30", "12:20" };
    int compareData = getInteger(s);
    List<String> result = new ArrayList<String>();
    int minDistance = Integer.MAX_VALUE;
    for (String tempStr : ss) {
    int tempdata = Math.abs(compareData - getInteger(tempStr));
    System.out.println(tempdata);
    if (minDistance > tempdata) {
    result.clear();
    result.add(tempStr);
    minDistance = tempdata;
    } else if (minDistance == tempdata) {
    result.add(tempStr);
    }
    }
    System.out.println(result);
    } public static int getInteger(String s) {
    String temp[] = s.split(":");
    int data = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
    return data;
    }
    }
      

  22.   

    我觉得,先对每行进行strtok冒号,比较小时的差值,找到差值最近的,然后如果小时的差值相同,则先strch冒号,得到后面的为b,然后strtok冒号,得到前面的为a,然后time= a*60+b;
    比较。。
      

  23.   

    import java.util.Arrays;
    public class Test { /**
     * @param args
     */
     static String[] s=new String[]{"01:16","06:22","14:54","13:35","12:19","12:20" };
     static String[][] temp=new String[s.length][2];
     static int [][] inttemp=new int[s.length][2];
     static int [] timeTemp=new int[s.length];
     static int [] Abs=new int[s.length];
     static int [] sortAbs=new int[s.length];
    static int index;
     static void Sp()

    for(int i=0;i<s.length;i++)
    {

    temp[i]=s[i].split(":");

    }



    for(int i=0;i<s.length;i++)//将字符串数组转化成整形的数组 作为中介质
    {
    for(int j=0;j<temp[i].length;j++){
    inttemp[i][j]=Integer.valueOf(temp[i][j]);

    }}


    for(int i=0;i<inttemp.length;i++)//将字符串数组通过中介值转化成分
    {

    timeTemp[i]=inttemp[i][0]*60+inttemp[i][1];


    }


    }
     
     static int ABS(String san)//计算输入的值与时间数组中的差值

    try {int t= (Integer.valueOf(san.split(":")[0]))*60+Integer.valueOf(san.split(":")[1]);
     for(int i=0;i<timeTemp.length;i++)
    {
     Abs[i]=Math.abs(timeTemp[i]-t);

    }
    sortAbs=Arrays.copyOf(Abs,Abs.length);
     Arrays.sort(sortAbs);
    }
     catch (Exception e)
    {
    System.out.println("参数有误");
    }

    return sortAbs[0];
       }
    public static void main(String[] args) {

          Sp();
         
          String san="08:23";
          int t=ABS(san);
          for(int j=0;j<Abs.length;j++){
    if (Abs[j]==t){
    index=j;
    }

          }
          System.out.println("最近数值是"+s[index]);
         
           }}
    写的有点多......没有讲简洁
      

  24.   

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>int main()
    {
    char time[6][6] =  {{"01:16"},
    {"06:22"},
    {"14:54"},
    {"13:35"},
    {"12:19"},
    {"12:20"}};
    char input[6];
    printf("Please input a time!\n");
    scanf("%s" , input);
    int hour = atoi(strtok(input,":"));
    int minute = atoi(strtok(NULL,":"));
    if(hour >24 ||hour <0 || minute <0 || minute>60)
    {
    printf("The time you input is invalid!\n");
    return 0;
    }
    int T=60*hour+minute; int i,j;
    int temp=60*(atoi(strtok(time[0],":")))+atoi(strtok(NULL,":")) - T; if(temp<0)
    temp = -temp ; for(i=1;i<6;i++)
    {
    char buf[6] ;
    strcpy(buf,time[i]);
    int num;
    num = 60*(atoi(strtok(buf,":")))+atoi(strtok(NULL,":")) - T;
    if(num<0)
    num = -num;
    if(num<temp)
    {
    temp = num;
    j=i;
    }
    }
    printf("The nearest time is %s\n" , time[j] );
    return 0;
    }
      

  25.   

    public static int getMinute(String s) {
    int data = 0 ;
    try{
            String temp[] = s.split(":");
            data = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
    }
    catch(Exception e){
    return 0;
    }
            return data;
        } public static void main(String[] args) {
    String s = "12:18";
            String[] ss = { "12:28", "13:37", "12:16", "18:30", "12:20" };
            Map<Integer, String> map  = new HashMap<Integer, String>() ;
            List<Integer> list = new ArrayList<Integer>() ;
            int sMinute = getMinute(s) ;
            for (int i = 0; i < ss.length; i++) {
    int ssMinute = getMinute(ss[i]) ;
    int minute = Math.abs(sMinute - ssMinute) ;
    if(!list.contains(minute))
    list.add(minute) ;
    if(map.containsKey(minute)){
    map.put(minute, map.get(minute)+"&&"+ss[i]) ;
    }else{
    map.put(minute, ss[i]) ;
    }

    }
       
            Collections.sort(list, new Comparator<Integer>() { @Override
    public int compare(Integer o1, Integer o2) {
    return o1.intValue()-o2.intValue()  ;
    }
    });
    for (Integer key : list) {
    System.out.println(map.get(key)+"--"+key);
    } }
      

  26.   

    import java.lang.reflect.Array;
    import java.util.Arrays;/**
     * 类型转化和最后还原类型找到结果都可以抽取做来做方法会简化代码,我懒得弄啦。
     * 动用了2层FOR循环,貌似不是很效率 呵呵~
     * @author Rainy
     *
     */
    public class TimeCheck {
    public static void main(String[] args) {
    String[] times = { "01:16", "06:22", "14:54", "13:35", "12:19", "12:20" };
    int[] timesStr = new int[times.length + 1];
    int[] timesStrEnd = new int[times.length + 1];
    for (int i = 0; i < times.length; i++) {
    timesStr[i] = Integer.parseInt(times[i].split(":")[0]) * 60
    + Integer.parseInt(times[i].split(":")[1]);
    timesStrEnd[i] = timesStr[i];
    }
    timesStr[timesStr.length - 1] = 12 * 60 + 18;
    // 初值语句 时间格式字符串直接调用 转化格式方法转化成INT就OK,像上面一样,懒得写了。
    int m = 12 * 60 + 18;
    // 升序排列
    Arrays.sort(timesStr);
    for (int i = 0; i < timesStr.length; i++) {
    if (timesStr[i] == m) {
    if (m - timesStr[i - 1] >= timesStr[i + 1] - m) {
    for (int j = 0; j < timesStrEnd.length; j++) {
    if (timesStrEnd[j] == timesStr[i + 1]) {
    System.out.println("与m距离最近的时间是:" + times[j]);
    }
    }
    } else {
    for (int j = 0; j < timesStrEnd.length; j++) {
    if (timesStrEnd[j] == timesStr[i + 1]) {
    System.out.println("与m距离最近的时间是:" + times[j]);
    }
    }
    }
    }
    }
    }
    }
      

  27.   

    public static void main(String[] args) {
       String timePoint = "12:18" ;
           String[] timeArr = { "12:28", "13:37", "12:16", "18:30", "12:17" } ;
           //以00:00分为参照,把时间都转成分钟
           String[] temp = timePoint.split(":") ;
           Integer timePointNum = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]) ;        
           Integer timePointItemNum = 0 ;
           Integer minNum = 24*60 ;
           Integer minIndex = -1;
           Integer minNumTemp = 0;
           for (int i=0,len=timeArr.length; i < len; i++){
            temp = timeArr[i].split(":");
            timePointItemNum = Integer.valueOf(temp[0]) * 60 + Integer.valueOf(temp[1]);
            minNumTemp =  Math.abs(timePointItemNum-timePointNum);       
            if(minNumTemp<minNum){
            minNum = minNumTemp;
            minIndex = i;
           }
           }
           System.out.println(timeArr[minIndex]);
    }
      

  28.   

    import java.util.*;
    import java.text.*;public class Test8 { public static void main(String[] args) throws Exception {
    String f = "12:18";
    String[] s = {"12:28", "13:37", "12:16", "18:30", "12:20"};
    SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
    Date[] d = new Date[s.length];
    for(int i=0; i<s.length; i++) {
    d[i] = sdf.parse(s[i]);
    }
    Date date = sdf.parse(f);
    Long[] t = new Long[s.length];

    for(int i=0; i<s.length; i++) {
    t[i] = d[i].getTime() - date.getTime();
    t[i] = Math.abs(t[i]);
    } long l = t[0];
    int j = 0;
    for(int i=1; i<s.length; i++) {
    if(t[i] < l) {
    l = t[i];
    j = i;
    }
    }
    System.out.println(s[j]);
    }
    }
      

  29.   

    c++
    #include <iostream>
    using namespace std;int fabs(int value)
    {
    if(value < 0)
    return -value;
    return value;
    }void main()
    {
    char *ptime = "12:18";
    char *chtime[] = {"01:16", "06:22", "14:54", "13:35", "12:19", "12:20"};
    int time;
    int inttime[6];
    int hour, minute; sscanf(ptime, "%d:%d", &hour, &minute);
    time = hour*60+minute; for(int i = 0; i < 6; ++i)
    {
    sscanf(chtime[i], "%d:%d", &hour, &minute);
    inttime[i] = hour*60+minute;
    } int tmp = fabs(time-inttime[0])%(12*60);
    int j = 0;
    for(int k = 1; k < 6; ++k)
    {
    if(tmp > (time-inttime[k]) % (12*60))
    {
    tmp = fabs(time-inttime[k]) % (12*60);
    j = k;
    }
    }

    cout<< chtime[j] <<endl;
    }
      

  30.   

    [Quote=引用 45 楼  的回复:]是if(tmp > fabs(time-inttime[k]) % (12*60)),不小心写错了
      

  31.   

    if (minDistance > tempdata) {
                    result.clear();
                    result.add(tempStr);
                    minDistance = tempdata;
                } else if (minDistance == tempdata) {
                    result.add(tempStr);
                }
    这几行代码是什么意思呢,干嘛要这样写?
      

  32.   


    package cucumber.entity;import java.util.Arrays;public class FindOut {
    static String[] arr = {"01:16","06:22","14:54","13:35","12:19","12:20"};
    public static int clockToInt(String str){
    String[] arr = str.split(":");
    return Integer.parseInt(arr[0]) * 60 +  Integer.parseInt(arr[1]);
    }

    public static String findInArr(String key, String[] arr){
    int start = 0;
    int end = arr.length - 1;
    if(clockToInt(key)  < clockToInt(arr[start]) || clockToInt(key) > clockToInt(arr[end])){
    return (clockToInt(arr[start]) + 24 * 60 - clockToInt(key)) >  (clockToInt(arr[end]) - clockToInt(key)) ? arr[start] : arr[end];
    }
    while(start <= end){
    if(start == end - 1){
    break;
    }
    int middle = (start + end ) / 2;
    if(key.equals(arr[middle])){
    return key;
    }else if(clockToInt(key) < clockToInt(arr[middle])){
    end  = middle;
    }else{
    start = middle;
    }
    }
    return (clockToInt(key) - clockToInt(arr[start])) > (clockToInt(arr[end]) - clockToInt(key)) ? arr[end] : arr[start];
    }

    public static void main(String[] args) {
    Arrays.sort(arr);
    System.out.println(findInArr("0:00", arr));
    }
    }
      

  33.   

    一个O(n)的算法,
    定义以数组,int a[12][60],模拟一个时钟,
    即,a[0][17] 代表 12:18,
    1. 遍历时间数组,元素对应的a元素置为1,其他的0;
    2. 从给点时间点对应的数组a元素开始,向前一步,向后一步遍历,
    直到找到不为0的a元素,侧,该元素代表的时间点为离指定时间点最近的。
      

  34.   

    public class Demo {
    public static void main(String[] args) throws ParseException {
    String[] a = { "12:20", "13:40", "9:40", "3:50", "4:00", "3:12" };
    SimpleDateFormat sdf=new SimpleDateFormat("h:mm");
    List<Date> date=new ArrayList<Date>();
    for(String s:a){
    date.add(sdf.parse(s));
    }
    String s="3:30";
    Date d=sdf.parse(s);
    List<Long> l=new ArrayList<Long>();
    for(Date g:date){
    long q=g.getTime();
    long w=d.getTime();
    l.add(Math.abs(q-w));
    }
    List<Long> g=new ArrayList<Long>(l);
    Collections.sort(l);
    int i=g.indexOf(l.get(0));
    System.out.println(a[i]);
    }
    }
      

  35.   


    package java_test;import java.util.Date; 
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;public class datime { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    HashMap<String,Date>getdate = new HashMap<String, Date>();
    final String format2 = "yyyy-MM-dd HH:mm";
    String []muchtime={"01:16","06:22","14:54","13:35","12:19","12:20"};
        Date revule=null;
        Date vlues=null;
        SimpleDateFormat  sdf = new SimpleDateFormat(format2);
    for (int i = 0; i < muchtime.length; i++) {

    muchtime[i]="2012-6-2"+" "+muchtime[i];
       
      
    try {
    revule= sdf.parse(muchtime[i]);

    } catch (ParseException e) {

    System.out.println("error!");
    }
    getdate.put(muchtime[i],revule);



    }
    try {
    vlues=sdf.parse("2012-6-2"+" "+"12:18");
    } catch (ParseException e) {
    // TODO Auto-generated catch block
     System.out.println("error!");
    }

    muchtime=null;
    long date1=vlues.getTime();
     for (Map.Entry e:getdate.entrySet()) {
     Date date2=(Date) e.getValue();
     long date3 = date2.getTime();
     if(date1-date3<0){
     e.setValue(0-(date1-date3));
     
     }else{
     e.setValue(date1-date3);
     }
     
    }

     long a = 9223372036854775806L;
     for (Map.Entry e:getdate.entrySet()) {
     long date= (Long) e.getValue();
     if(a>date){
     a=date;
     }
     
     
      }
     
     for (Map.Entry e:getdate.entrySet()) {

     if(a== (Long) e.getValue()){
    String a1= (String)e.getKey();
    String a3 =a1.replaceAll("2012-6-2", "");
     System.out.println(a3);
     }
     
     }
     
     
      
          

    }}
      

  36.   


    package java_test;
    import java.text.SimpleDateFormat;
    import java.util.Date; 
    import java.util.HashMap;
    import java.util.Map;
    public class datime { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    HashMap<String,Date>getdate = new HashMap<String, Date>();
    final String format2 = "yyyy-MM-dd HH:mm";
    String []muchtime={"01:16","06:22","14:54","13:35","12:19","12:20"};
        Date revule=null;
        Date vlues=null;
        SimpleDateFormat  sdf = new SimpleDateFormat(format2);
    for (int i = 0; i < muchtime.length; i++) {

    muchtime[i]="2012-6-2"+" "+muchtime[i];
       
      
    try {
    revule= sdf.parse(muchtime[i]);

    } catch (Exception e) {

    System.out.println("error!");
    }
    getdate.put(muchtime[i],revule);



    }
    try {
    vlues=sdf.parse("2012-6-2"+" "+"12:18");
    } catch (Exception e) {
    // TODO Auto-generated catch block
     System.out.println("error!");
    }

    muchtime=null;
    long date1=vlues.getTime();
     for (Map.Entry e:getdate.entrySet()) {
     Date date2=(Date) e.getValue();
     long date3 = date2.getTime();
     if(date1-date3<0){
     e.setValue(0-(date1-date3));
     
     }else{
     e.setValue(date1-date3);
     }
     
    }

     long a = 9223372036854775806L;
     for (Map.Entry e:getdate.entrySet()) {
     long date= (Long) e.getValue();
     if(a>date){
     a=date;
     }
     
     
      }
     
     for (Map.Entry e:getdate.entrySet()) {

     if(a== (Long) e.getValue()){
    String a1= (String)e.getKey();
    String a3 =a1.replaceAll("2012-6-2", "");
     System.out.println(a3);
     }
     
     }
     
     
      
          

    }}
      

  37.   

    public static void main(String[] args) {
    String[] str={"12:31","13:40","14:50","23:50","12:33"};
    String s="13:32";
    List<Integer> l=new ArrayList<Integer>();
    for(String a:str){
    l.add(Math.abs(a.hashCode()-s.hashCode()));
    }
    List<Integer> t=new ArrayList<Integer>(l);
    Collections.sort(l);
    int i=t.indexOf(l.get(0));
    System.out.println(str[i]);
    }
      

  38.   

    不过有一个bug如果数组里面有个13:32那就不行了!
      

  39.   

    BUG多了去了 {"13:8","13:40","14:50","23:50","12:33"} String s="13:10";
    不用大脑思考问题?
      

  40.   

    我还没学hashcode的用法,不是很了解这种机制。哥们方便留个联系方式,请教下
      

  41.   

    加我联系方式又没用,我又不是API和源代码。具体翻API和源代码,然后你在回过头来看这段代码,你就知道问题了。
      

  42.   

    给一个我的思路,不用求和也不用转换,因为时间是24小时制的所以可以直接比较大小,不用小时+分钟求和或者转换为分钟
    public static void main(String[] args) {
    String[] str = {"01:16", "06:22", "14:54", "13:35","12:16", "12:19", "12:20"};
    String s = "12:18", mintime = s;
    int temp = Integer.parseInt(s.replace(":", "")), min = 2399;
    for (String time : str) {
    if (!time.matches("[0-9]{1,2}:[0-9]{1,2}")) continue;
    int tempmin = Math.abs(temp - Integer.parseInt(time.replace(":", "")));
    if (tempmin < min) {
    mintime = time; min = tempmin;
    }
    }
    System.out.println(mintime);
    }
      

  43.   


    package com.zf.target;import java.util.Arrays;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.Map;public class Test5 {

    public static String getNear(String target , String... dates){
    long targetTime = formatStringToTime(target);
    long[] shortTime = new long[dates.length]; //时间差
    Map<Long , String> map = new HashMap<Long , String>(); //保存时间差对应的时间
    for (int i = 0; i < dates.length; i++) {
    long time = formatStringToTime(dates[i]);
    shortTime[i] = Math.abs(targetTime - time); //取时间差的绝对值
    map.put(shortTime[i], dates[i]);
    }
    Arrays.sort(shortTime); //排序
    return map.get(shortTime[0]); //取最小值
    }

    public static long formatStringToTime(String str){
    String[] arr = str.replaceAll("(\\d+):(\\d+)", "$1,$2").split(",");
    Calendar c =  Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arr[0]));
    c.set(Calendar.MINUTE, Integer.parseInt(arr[1]));
    c.set(Calendar.SECOND, 0);
    return c.getTimeInMillis();
    }

    public static void main(String[] args) {;
    System.out.println(getNear("12:03" , new String[]{"01:16" 
    , "06:22" , "14:54" , "13:35" , "12:19" , "12:20"
    , "15:01" , "15:03"
    }));
    }
    }
      

  44.   

    更正多个时间差相同的问题 , 判断格式那些小问题, 没必要写出来了吧。package com.zf.target;import java.util.Arrays;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Vector;public class Test5 {

    public static List<String> getNear(String target , String... dates){
    long targetTime = formatStringToTime(target);
    long[] shortTime = new long[dates.length]; //时间差
    Map<Long , List<String>> map = new HashMap<Long , List<String>>(); //保存时间差对应的时间
    for (int i = 0; i < dates.length; i++) {
    long time = formatStringToTime(dates[i]);
    shortTime[i] = Math.abs(targetTime - time); //取时间差的绝对值
    if(map.containsKey(shortTime[i])) //如果该时间差已经存在
    map.get(shortTime[i]).add(dates[i]);
    else{
    List<String> list =  new Vector<String>();
    list.add(dates[i]);
    map.put(shortTime[i], list);
    }
    }
    Arrays.sort(shortTime); //排序
    return map.get(shortTime[0]); //取最小值 
    }

    public static long formatStringToTime(String str){
    String[] arr = str.replaceAll("(\\d+):(\\d+)", "$1,$2").split(",");
    Calendar c =  Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arr[0]));
    c.set(Calendar.MINUTE, Integer.parseInt(arr[1]));
    c.set(Calendar.SECOND, 0);
    return c.getTimeInMillis();
    }

    public static void main(String[] args) {;
    System.out.println(Arrays.toString((getNear("15:02" , new String[]{"01:16" 
    , "06:22" , "14:54" , "13:35" , "12:19" , "12:20"
    , "15:01" , "15:03"
    })).toArray()));
    }
    }
      

  45.   

    我觉得不能直接把:去掉变成Integer类型比大小
    因为比如是基数是12:59   那么13:00只比它大1秒,12:57比它小两秒
    而Integer是十进制的数字,分钟是60进制的数字 这里只会选取12:57而不选取13:00所以我给出如下源码
    public static void main(String[] args) throws ParseException, IOException {
    String time = "12:28";
    String[] times = {"01:16","06:22","14:54","13:35","12:19","12:20"};
    DateFormat date = new SimpleDateFormat("mm:ss");
    long timel = date.parse(time).getTime();
    long[] timesl = new long[times.length + 1];

    for (int i = 0; i < timesl.length-1; i++)timesl[i] = date.parse(times[i]).getTime();
    timesl[times.length] = timel;
    Arrays.sort(timesl);
    long min=0,max=0;
    for (int i = 0; i < timesl.length; i++)
    if(timesl[i] == timel){
    if(i != 1)max = timesl[i-1];
    if(i != timesl.length-2)min = timesl[i+1];
    }

    if((max-timel)<=(timel-min))
    System.out.println("这个时间是: " + date.format(new Date(min)));
    else
    System.out.println("这个时间是: " + date.format(new Date(max)));

    }
    如果有00:00存在 需要再加几行判断
      

  46.   

    一个O(n)的算法,
    定义数组,int a[24][60],模拟一个时钟,
    即,a[x][y] 就是x点y分
    1. 遍历时间数组,元素对应的a元素置为1,其他的0;
    2. 从给点时间点对应的数组a元素开始,向前一步,向后一步遍历,
    直到找到不为0的a元素,侧,该元素代表的时间点为离指定时间点最近的。
      

  47.   


            非常感谢34楼给出的答案,好像有两个bug:
            1.没有对j进行初始化,如果time[0][6]是最接近的时间的话,不初始化j程序无法正确运行;
            2.没有考虑到time[6][6]和用户输入中包含有:00:XX特殊情况的处理。
            以下是我改过的程序,请大家看下还有什么问题没有。
      

  48.   


    刚才没有粘上去,再试一次:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>int main()
    {
        char time[6][6] =  {{"02:16"},
                            {"06:22"},
                            {"14:54"},
                            {"13:35"},
                            {"23:19"},
                            {"00:20"}};
        char input[6];
        printf("Please input a time!\n");
        scanf("%s" , input);
        int hour = atoi(strtok(input,":"));
        int minute = atoi(strtok(NULL,":"));
    printf("hour = %d\n",hour);
        if(hour >24 ||hour <0 || minute <0 || minute>60)
        {
            printf("The time you input is invalid!\n");
            return 0;
        }
        int T=(hour == 0) ? 60*(hour+24)+minute : 60*hour+minute; //对输入为00:XX特殊情况的处理
    printf("T = %d\n",T);    int i,j,t_hour,t_minute;
    j=0; //如果最接近的时间为time[0],则需要对j赋0。
        int temp=60*(atoi(strtok(time[0],":")))+atoi(strtok(NULL,":")) - T;    if(temp<0)
            temp = -temp ;    for(i=1;i<6;i++)
        {
            char buf[6] ;
            strcpy(buf,time[i]);
    t_hour = atoi(strtok(buf,":"));
    t_minute = atoi(strtok(NULL,":"));
            int num;
    printf("%d. t_hour = %d\n",i,t_hour);
    if(t_hour == 0) //对time[6][6]中时为0特殊情况的处理
    num = 60*(24+t_hour) + t_minute - T;
    else 
    num = 60*t_hour + t_minute - T;
            if(num<0)
                num = -num;
            if(num<temp)
            {
                temp = num;
                j=i;
            }
        }
        printf("The nearest time is %s\n" , time[j] );
        return 0;
    }
      

  49.   

    这种题似乎很常见,用map特别简单就实现了
      

  50.   

    哥们,做题不能看着哪个答案眼熟,就向哪个答案靠近啊!
    假如我设定的时间为11:58 ——> 69
    而选项为14:00 ——> 14 ,和 10:00 ——> 10 .
    难道11:58离14:00近一些?
      

  51.   

    hh:mm(设为H:M)
    给定时间Hx:Mx
    待测时间Hy:My
    相差时间|60*Hx-60*Hy+Mx-My|=|60(Hx-Hy)+(Mx-My)|
    然后取最小值即可,可能有2个答案
      

  52.   

    排序的复杂度比较大,转成分钟复杂度低。
    而却字符串排序是和float是不同的。9:00>7:00>12:00这是字符串的排序