PROGRAMING/C#

[Algorithm] Two Sum

donghunl 2024. 4. 20. 17:02
반응형

Question:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

 

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

 

배열안에서 두 요소를 더하여 타겟값을 만들어내는 문제입니다. 

 

 

Solution:

반복문을 두 번 사용하여 각각의 요소를 더하여 타겟값과 비교를 하도록 합니다. 단, 두번째 요소의 경우 첫번째와 겹치지 않도록 i+1으로 시작합니다. 타겟값과 일치하는 결과가 나오면 Temp리스트에 담고 반복문을 종료시킵니다. 결과값을 배열의 인덱스를 배열값으로 원하므로 결과를 담은 Temp리스트를 배열로 변경하고 반환시킵니다.

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        int[] answer = new int[] {};
        int num1 = 0;
        int num2 = 0;
        List<int> tempList = new List<int>();

        for(int i = 0; i < nums.Length; ++i) { // 첫번째 인덱스를 위한 반복문
            for(int j = i+1; j < nums.Length; ++j) { // 두번째 인덱스를 위한 반복문
                num1 = nums[i]; 
                num2 = nums[j];
                if(num1 + num2 == target) // 타겟값과 두개의 합을 비교
                {
                    tempList.Add(i);
                    tempList.Add(j);
                    break; // 반복문을 종료
                }
            }
        }
        answer = tempList.ToArray(); // 배열로 변환
        
        return answer;
    }
}

Use the loop statement twice to add each element and compare it with the target value. However, for the second element, start with i+1 so that it does not overlap with the first element. If you get a result that matches the target value, put it in the Temp list and end the loop statement. Since you want the result value as the array, change the Temp list to the array and return it.

반응형

'PROGRAMING > C#' 카테고리의 다른 글

[Algorithm] Palindrome Number  (76) 2024.04.27
[Algorithm] Integer to Roman  (100) 2024.04.25
[Algorithm] Median of Two Sorted Arrays  (132) 2024.04.22
[Algorithm] Add Two Numbers  (84) 2024.04.21
[Algorithm] Merge Sorted Array  (93) 2024.04.19