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

    Compare two version numbers version1 and version1.
    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.
    The . character does not represent a decimal point and is used to separate number sequences.
    For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

    Here is an example of version numbers ordering:

    0.1 < 1.1 < 1.2 < 13.37


    解法:


    2,采用“.”分离时,要加上“\.”
    3,数组没有赋值时,默认为0
    package Leetcode;
    
    public class CompareVersionNumbers {
        public int compareVersion(String version1, String version2) {
            String[] ver1=version1.split("\.");
            String[] ver2=version2.split("\.");
            int maxlength=Math.max(ver1.length, ver2.length);
            
            int[] ints1 = new int[maxlength];
            
            for (int i=0; i < maxlength; i++) {
                ints1[i] = Integer.parseInt(ver1[i]);
            }
            int[] ints2 = new int[maxlength];
            for (int i=0; i < maxlength; i++) {
                ints2[i] = Integer.parseInt(ver2[i]);
            }
            for(int i=0;i<maxlength;i++){
                if(ints1[i]>ints2[i]){
                    return 1;
                }
                else if(ints1[i]<ints2[i]){
                    return -1;
                }
            }
            return 0;
        }
    }

     2017/8/19 更新, clean code

    class Solution {
        public int compareVersion(String version1, String version2) {
            String[] ints1 = version1.split("\.");
        String[] ints2 = version2.split("\.");
        
        int length = Math.max(ints1.length, ints2.length);
        for (int i=0; i<length; i++) {
            Integer v1 = i < ints1.length ? Integer.parseInt(ints1[i]) : 0;
            Integer v2 = i < ints2.length ? Integer.parseInt(ints2[i]) : 0;
            int compare = v1.compareTo(v2);
            if (compare != 0) {
                return compare;
            }
        }
        
        return 0;
        }
    }

      

  • 相关阅读:
    利用QObject反射实现jsonrpc
    使用libuv实现生产者和消费者模式
    std::function赋值的几种方法
    Qt postEvent
    Qt由pcm数据生成wav文件
    Qt websocket协议的实现
    Python中json.dump() 和 json.dumps()的区别
    Appium环境搭建(Mac)
    Mac上搭建Python集成环境
    Mac OS终端利器iTerm2(完美替代bash)
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/4186486.html
Copyright © 2011-2022 走看看