zoukankan      html  css  js  c++  java
  • Compare Version Numbers

    Compare Version Numbers

    问题:

    Compare two version numbers version1 and version2.
    If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

    You may assume that the version strings are non-empty and contain only digits and the . character.

    思路:

      简单的数学推导而已,就是需要考虑的case比较多

    我的代码:

    public class Solution {
        public int compareVersion(String version1, String version2) {
            if(version1 == null && version2 == null)    return 0;
            if(version1 == null)    return -1;
            if(version2 == null)    return 1;
            String[] ones = version1.split("\.");
            String[] twos = version2.split("\.");
            int i = 0;
            for(; i < ones.length && i < twos.length; i++)
            {
                int one = Integer.valueOf(ones[i]);
                int two = Integer.valueOf(twos[i]);
                if(one == two) continue;
                if(one > two) return 1;
                if(one < two) return -1;
            }
            while(i < ones.length)
            {
                int one = Integer.valueOf(ones[i]);
                if(one != 0) return 1;
                i++;
            }
            while(i < twos.length)
            {
                int two = Integer.valueOf(twos[i]);
                if(two != 0) return -1;
                i++;
            }
            return 0;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public int compareVersion(String version1, String version2) {
            String[] v1 = version1.split("\.");
            String[] v2 = version2.split("\.");
    
            int longest = v1.length > v2.length? v1.length: v2.length;
    
            for(int i=0; i<longest; i++)
            {
                int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0;
                int ver2 = i<v2.length? Integer.parseInt(v2[i]): 0;
    
                if(ver1> ver2) return 1;
                if(ver1 < ver2) return -1;
            }
            return 0;
        }
    }
    View Code

    学习之处:

    • 思路和方法都不难,就是需要考虑到的情况有点多,需要考虑仔细啦
    • 他人的代码真简洁,简洁来源于int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0;好好学习一下下。
    • 让我联想到了Comparator 接口,接口的使用方法,如下代码所示,另外假如A的值大于B,你返回1。这样调用Collections.sort()方法就是升序;假如A的值大于B,你返回-1。这样调用Collections.sort()方法就是降序。
    public class StringComparator implements Comparator<String>{
        @Override
        public int compare(String A, String B) {
               return 0;      
        }
    }
  • 相关阅读:
    bzoj2888: 资源运输
    [ SDOI 2009 ] HH的项链 & [ HEOI 2012 ] 采花
    [ POI 2017 ] Podzielno
    [ HAOI 2011 ] Problem A
    [ SDOI 2011 ] 打地鼠
    [ SCOI 2007 ] Perm
    [ POI 2011 ] Dynamite
    [ BZOJ 3038 & 3211 / SPOJ GSS4 ] 上帝造题七分钟2 / 花神游历各国
    [ BZOJ 3445 ] Roadblock
    [ ZJOI 2006 ] Mahjong
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4338212.html
Copyright © 2011-2022 走看看