题目分析来自“待字闺中”微信公众平台。
题目:排序只有1,2,3三个元素的数组,不能统计1,2,3的个数。
初学python。
第一种方法:
__author__ = 'ledao' arr = [2, 1, 1, 3, 1, 1, 3, 3, 2] def findLeftFirstNon1(arr, startPos): for i in xrange(startPos, len(arr)): if 1 != arr[i]: return i print 'Error occurs!' return -1 def findRightFirstNon3(arr, startPos): for i in xrange(startPos, -1, -1): if 3 != arr[i]: return i print 'Error occurs!' return -1 def sort(arr): p1 = findLeftFirstNon1(arr, 0) p3 = findRightFirstNon3(arr, len(arr)-1) p2 = -1 while True: for i in xrange(p1, p3+1): p2 = i if 1 == arr[i]: arr[i] = arr[p1] arr[p1] = 1 p1 = findLeftFirstNon1(arr, p1+1) break if 3 == arr[i]: arr[i] = arr[p3] arr[p3] = 3 p3 = findRightFirstNon3(arr, p3-1) break if p2 >= p3: break print 'Completed!' sort(arr) print arr