일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 유니티
- 노마드코더
- 자바
- Unity
- 쿠킹덤
- programmers
- oracle
- 티스토리챌린지
- HTML
- 웹개발
- JavaScript
- 자바스크립트
- Java
- SQL
- 오블완
- Spring
- 개발자
- 쿠키런킹덤공략
- 크리스마스
- Eclipse
- 딥러닝
- 홀리데이익스프레스
- MySQL
- 프로그래머스
- 이클립스
- 쿠킹덤공략
- 쿠키런킹덤크리스마스
- edwith
- dart
- 쿠키런킹덤
Archives
- Today
- Total
Dev study and notes
리트코드 0001 두 수의 합 LEETCODE 1. Two Sum 본문
반응형
1. 두 수의 합
1. Two Sum
Difficulty | Topics | Hints | URL |
---|---|---|---|
Easy | Array``Hash Table |
3 | https://leetcode.com/problems/two-sum/description/ |
목차
설명
- 정수 배열
nums
와 정수target
이 주어졌을 때, 합이target
이 되는 두 숫자의 인덱스를 반환하세요. - 각 입력에는 정확히 한 가지 솔루션이 있다고 가정할 수 있으며, 같은 요소를 두 번 사용할 수는 없습니다.
- 답변은 어떤 순서로 반환해도 됩니다.
예시
예시 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
예시 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
예시 3:
Input: nums = [3,3], target = 6
Output: [0,1]
제약 조건
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
- 정확히 하나의 유효한 답변이 존재합니다.
추가 문제
- 시간 복잡도가
O(n^2)
보다 적은 알고리즘을 생각할 수 있나요?
Solutions
JAVA (Array)
class Solution {
public int[] twoSum(int[] nums, int target) {
int numsLength = nums.length;
for (int i = 0; i < numsLength - 1; ++i) {
for (int j = i + 1; j < numsLength; ++j) {
if (target == nums[i] + nums[j]) {
return new int[]{i, j};
}
}
}
return new int[2];
}
}
JAVA (Hash Table)
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[0];
}
}
반응형
'LEETCODE' 카테고리의 다른 글
리트코드 0003 중복되지 않는 가장 긴 부분 문자열 찾기 LEETCODE 3. Longest Substring Without Repeating Characters (0) | 2024.12.03 |
---|---|
리트코드 0002 두 수 더하기 LEETCODE 2. Add Two Numbers (0) | 2024.12.03 |
LEETCODE 0001 TWO SUM (0) | 2024.12.02 |
Comments