LeetCode#165 Compare Version Numbers

Problem Definition:

  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.
  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

Solution: 

1 def compareVersion(self,version1, version2):
2         f1=map(lambda x: int(x) ,version1.split('.'))
3         f2=map(lambda x: int(x) ,version2.split('.'))
4         f1+=([0]*(len(f2)-len(f1)))
5         f2+=([0]*(len(f1)-len(f2)))
6         return 1 if f1>f2 else (-1 if f1<f2 else 0)

Tricks:

1) b=[0]*a,当a是大于0的整数时,b是一个有a个0的数组;当a<=0,b==[ ]

2) a=[1,2,3]  b=[4,5,6]  a+b==[1,2,3,4,5,6]  相当于a.extend(b)

3) a=[1,4] b=[2,3]  则a<b

    a=[1,4] b=[1,3]      则a>b

  a=[1]  b=[0,2]        则a>b

    a=[1]  b=[1,0]    则a<b

  从左边其,从俩数组a,b中分别取同下标的元素ai,bi;比较其大小,若ai>bi,则a>b;若ai,bi,则a<b;否则下标加1,继续下一次比较...

  如果到了一个数组结束仍未比出大小,则判定先结束的数组小于后结束的。

4)三目运算可以这么嵌套  a=b if c else ( d if e else f)

 

 

...应该算是...干货吧...

 

posted @ 2015-07-20 14:49  曾可爱  阅读(125)  评论(0编辑  收藏  举报