HackerRank Lily's Homework
https://www.hackerrank.com/challenges/lilys-homework/problem
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def lilysHomework(arr):
# Write your code here
# change = True
# ans = 0
# for i in range(len(arr)):
# if not change:
# break
# change = False
# for j in range(len(arr) - i - 1):
# if arrj > arrj + 1:
# arrj, arrj + 1 = arrj + 1, arrj
# ans += 1
# change = True
# return ans // 2
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def lilysHomework(arr):
# Write your code here
# create function to find no. of swaps
def no_of_swaps(arr):
indexmap = {}
for i in range(len(arr)):
indexmap[arri] = i
# print(indexmap)
# {2: 0, 5: 1, 3: 2, 1: 3}
# sort the array
# arr -> 2, 5, 3, 1
# sorted_arr -> 1, 2, 3, 5
sorted_arr = sorted(arr)
result = 0
for i in range(len(arr)):
if arri != sorted_arri: # 2 != 1
result += 1
# swap element index
swap_index = indexmap[sorted_arri] # 3
# update swapping index
indexmap[arri] = swap_index
# swap operation
arri, arrswap_index = arrswap_index, arri
return result
normal_order = no_of_swaps(arr::)
reverse_order = no_of_swaps(arr::-1)
return min(normal_order, reverse_order)
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=eeoEqIKhYLI
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
# 3 4 2 5 1
# 5 4 2 3 1
# 5 4 3 2 1
def lilysHomework(arr):
# Write your code here
ans = bubble_sort(arr)
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()