https://leetcode.com/problems/left-and-right-sum-differences/description/
Left and Right Sum Differences - LeetCode
Can you solve this real interview question? Left and Right Sum Differences - Given a 0-indexed integer array nums, find a 0-indexed integer array answer where: * answer.length == nums.length. * answer[i] = |leftSum[i] - rightSum[i]|. Where: * leftSum[i] is
leetcode.com

배열이 주어지고
왼쪽에서부터 값들을 더해서 배열 하나 만들고
오른쪽에서부터 더해서 배열 하나 만들어서
두 배열의 차의 절대값을 배열로 리턴.
import kotlin.math.abs
class Solution {
    fun leftRigthDifference(nums: IntArray): IntArray {
        val leftArray = IntArray(nums.size); 
        val rightArray = IntArray(nums.size)
        var left = 0; var right = 0
        val ansArray = IntArray(nums.size)
		// 처음부터 계산
        for(i in 0 until nums.size) {
            leftArray[i] = left
            left += nums[i]
        }
		
        // 끝에서부터 계산
        for(i in nums.size-1 downTo 0) {
            rightArray[i] = right
            right += nums[i]
        }
   
   		// 절대값 계산
        for(i in 0 until nums.size) {
            ansArray[i] = abs(leftArray[i] - rightArray[i])
        }
        
        return ansArray;
    }
for문 아래서 탐색할때는
downTo를 사용
https://hwan-shell.tistory.com/244
Kotlin] for문, while문 사용법
1. for문 코틀린 for문은 다양한 방식으로 작성될 수 있습니다. 1) 일반적인 for문fun main(args:Array) { for(i: Int in 1..10) print("$i ") //output : 1, 2, 3, 4, 5 ... 10 val len: Int = 5 for(i in 1..len) print("$i ") //output : 1, 2,
hwan-shell.tistory.com
'IT > 알고리즘' 카테고리의 다른 글
| 76] ★ Leetcode 1071. Greatest Common Divisor of Strings Kotlin (0) | 2023.04.11 | 
|---|---|
| 75] Leetcode 2413. Smallest Even Multiple Kotlin (0) | 2023.04.10 | 
| 73] Leetcode 2011. Final Value of Variable After Performing OperationsEasy1.1K151 #Kotlin (0) | 2023.04.05 | 
| 71] Leetcode 2469. Convert the Temperature (0) | 2023.04.04 | 
| 70] Leetcode 1929. Concatenation of Array (0) | 2023.04.03 | 
										
									
										
									
										
									
										
									
댓글