[Medium] Minimum Swaps 2 (Hackerrank, javascript, arrays, sorting)

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Minimum Swaps 2 Problems starts from @7:15

owaisqureshi
Автор

Hi Alexandr,
i used the code below and it works. I think it is running O(n) because every iteration i am putting a number in its correct position. However,
i dont know how to proof that it will generate the minimum steps to sort the array. I just know it works because it passed all testcases. It was a blind intuitive guess. Can you help me understand it?

int minimumSwaps(vector<int> arr) {
int i = 0;
int numswaps = 0;
while(i<arr.size())
{
if(arr[i] != i+1){
swap(arr[i], arr[arr[i]-1]);
numswaps++;
}
else{
i++;
}
}
return numswaps;
}

Dgsrgv
Автор

Can't hear a word the second guy is saying unfortunately

nicholasdrew
Автор

def swap(fro, to, arr):
a = arr[fro]
arr[fro] = arr[to]
arr[to] = a

def minimumSwaps(arr):
min_val = min(arr)
count = 0
for i in range(len(arr)-1):
# LOOP
if arr[i] != min_val:
swap(i, arr.index(min_val), arr)
count += 1; min_val += 1
else:
min_val += 1
return count


BROTHER THE ABOVE CODE SHOWING ME "TIMEOUT ERR" IN LAST 4-5 TEST CASE'S (IN MINIMUM SWAP PROBLEM) AND I THINK IT'S " Time complexity IS O(N) " i think which better than ur code can u plzzz help me in reducing it complexity

vinayaktyagi
visit shbcf.ru