码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Almost Sorted

时间:2015-03-18 06:26:21      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

Nothing special, just some corner cases

n = int(input())
arr = [int(i) for i in input().strip().split()]

# Collect 
rec = []
i = 0
while i < n - 1:
    if arr[i] > arr[i + 1]:
        inx = i
        cnt = 1
        while i < n - 1 and arr[i] > arr[i + 1]:
            cnt += 1
            i += 1
        rec.append((inx, cnt))
    else:
        i += 1

# Check
if len(rec) == 1:
    if rec[0][1] == 2:
        if rec[0][0] + 1 < n - 1 and arr[rec[0][0]] > arr[rec[0][0] + 2]:
            print ("no")
        else:
            print ("yes")
            print ("swap %d %d" % (rec[0][0] + 1, rec[0][0] + 2))
    elif rec[0][1] > 2:
        if rec[0][0] + rec[0][1] - 1 < n - 1 and arr[rec[0][0]] > arr[rec[0][0] + rec[0][1]]:
            print ("no")
        else:
            print ("yes")
            print ("reverse %d %d" % (rec[0][0] + 1, rec[0][0] + rec[0][1]))
elif len(rec) == 2 and rec[0][1] == 2 and rec[1][1] == 2:
    print ("yes")
    print ("swap %d %d" % (rec[0][0] + 1, rec[1][0] + 2))
else:
    print ("no")

HackerRank - Almost Sorted

标签:

原文地址:http://www.cnblogs.com/tonix/p/4346126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!