Algorithm/Leetcode, Lintcode, HackerRank, etc.(29)
-
2717. Semi-Ordered Permutation
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 { ..
2023.06.05 -
2541. Minimum Operations to Make Array Equal II
two arrays and integer value k are provided. the thing you need to do is to figure out the minumum number of changes by applying operation. the operation is as follows. in the first array, nums1 pick two indices i, j apply nums1[i] + k, nums1[j] - k and check the nums1 and the nums2 are equal, if so, then return the number of operations until then. Python class Solution: def minOperations(self, ..
2023.01.29 -
2545. Sort the Students by Their Kth Score
Python class Solution: def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: return sorted(score, key=lambda p: p[k], reverse=True) Kotlin class Solution { fun sortTheStudents(score: Array, k: Int): Array { val res = score.sortedByDescending { it[k] } return res.toTypedArray() } }
2023.01.29 -
2544. Alternating Digit Sum
Kotlin class Solution { fun alternateDigitSum(n: Int): Int { val s = n.toString() var sum: Int = 0 var toggle: Boolean = true for (i in 0 until s.length) { val digit = Character.getNumericValue(s[i]) if (true == toggle) { sum += digit } else { sum += -1 * digit } toggle = !toggle } return sum } }
2023.01.28 -
2255. Count Prefixes of a Given String
Kotlin class Solution { fun countPrefixes(words: Array, s: String): Int { var cnt = 0 for (word in words) { if (word.length > s.length) { continue } var is_same = true for (i in 0 .. word.length - 1) { if (word[i] != s[i]) { is_same = false break } } if (true == is_same) { cnt += 1 } } return cnt } } Python class Solution: def countPrefixes(self, words: List[str], s: str) -> int: cnt = 0 for wor..
2023.01.26 -
2269. Find the K-Beauty of a Number
Kotlin class Solution { fun divisorSubstrings(num: Int, k: Int): Int { var s: String = num.toString() if (s.length in..
2023.01.26