티스토리 뷰
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
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
[Leetcode] 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers (1) | 2024.03.21 |
---|---|
[Leetcode] 1631. Path With Minimum Effort (0) | 2024.03.15 |
[Leetcode] 131. Palindrome Partitioning (0) | 2024.03.13 |
[Leetcode] 343. Integer Break (0) | 2024.03.09 |
[Leetcode] 146. LRU Cache (0) | 2024.03.06 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백트레킹
- DFS
- 알고리즘
- 동적계획법
- level2
- java
- 구현
- Programmerse
- 누적합
- LeetCode
- 백준
- 파이썬
- 넓이 우선 탐색
- 수학
- 그래프
- 동적 계획법
- 자바
- 배열
- BFS
- DP
- 재귀호출
- 조합
- spring-boot
- BaekJoon
- Greedy
- JSCODE
- Python
- 이론
- 문자열
- 그리디
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함