2717. Semi-Ordered Permutation

2023. 6. 5. 08:15Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형
func swap(val1 *int, val2 *int) {
    temp := *val1
    *val1 = *val2
    *val2 = temp
}

func semiOrderedPermutation(nums []int) int {
    i := 0
    one_idx := -1
    n_idx := -1
    cnt := 0

    for idx, val := range nums {
        if val == 1 {
            one_idx = idx
        }
    }

    i = one_idx

    for i > 0 {        
        swap(&nums[i - 1], &nums[i])
        cnt += 1
        i -= 1
    }

    for idx, val := range nums {
        if val == len(nums) {
            n_idx = idx
        }
    }

    i = n_idx

    for i < len(nums) - 1 {        
        swap(&nums[i], &nums[i + 1])
        cnt += 1
        i += 1
    }

    return cnt
}
반응형