티스토리 뷰

알고리즘/Leetcode

[Leetcode] 1. Two Sum

응애~ 개발자 2024. 3. 5. 04:34
728x90
반응형

문제 요약

  • 알고리즘 분류: 브루트포스, 배열
  • 난이도: easy
  • 문제내용:
    • nums 배열 2개 뽑아서 target 숫자 맞는 인덱스 위치를 반환 하여라.
  • 사이트 주소: https://leetcode.com/problems/two-sum

문제풀이

 이번 문제는 간단한 배열 탐색이다. 구현은 아래와 같은 방식으로 하면 된다.

1.  이중 반복문으로 한다.

   - 첫번째는 배열의 길이 만큼 한다.

   - 두번째는 탐색 위치 i+1부터 배열 길이 탐색한다.

2. 두개 배열 위치에서 합해서 target 값이 같으면 배열 위치 반환한다.

 

Code

Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        length = len(nums)
        for i in range(length):
            for j in range(i + 1, length):
                if(nums[i] + nums[j]) == target:
                    return [i, j]

Java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        for(int i = 0; i < length; i++) {
        	for(int j = i + 1; j < length; j++) {
        		if(nums[i] + nums[j] == target) {
        			return new int[] {i, j};
        		}
        	}
        }
        
        return null;
    }
}

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함