문제
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].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
- 2 <= nums.length <= 104
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- Only one valid answer exists.
https://leetcode.com/problems/two-sum/
Two Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이
이중 for문을 통해 한번씩 비교해 나가는 방법을 이용했다.
답이 되는 경우가 한가지 밖에 없다고 해서 배열의 0번 숫자와 1~끝까지 더해보고, 1번 숫자와 2~끝가지 더해보는 식으로 이중 for문을 이용했다.
for문을 돌리면서 Map에 target에서 nums배열에 있는 값을 뺀 결과와 인덱스를 저장해 놓고, 다음 nums배열의 숫자가 Map에 있는지 contiains를 통해 확인하는 형식으로 하면 for문을 하나만 사용할 수 있을 것 같긴 하다.
코드
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
boolean flage = false;
for(int i = 0; i < nums.length; i++) {
res[0] = i;
for(int j = i+1; j < nums.length; j++) {
if(nums[res[0]] + nums[j] == target) {
res[1] = j;
flage = true;
break;
}
}
if(flage) {
break;
}
}
return res;
}
}
결과
'LeetCode' 카테고리의 다른 글
4. Median of Two Sorted Arrays (0) | 2022.02.06 |
---|---|
3. Longest Substring Without Repeating Characters 수정 (0) | 2022.01.21 |
3. Longest Substring Without Repeating Characters (0) | 2022.01.16 |
9. Palindrome Number (0) | 2022.01.16 |
2. Add Two Numbers (0) | 2022.01.16 |