728x90
문제
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문을 활용하여 문제를 해결한다.
i : 0 ~ num.length-1
j : i+1 ~ num.length
모든 범위를 확인하며 nums[i] + nums[j] 가 target이 되는 경우 답을 answer에 저장하고 리턴한다.
코드
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
answer[0] = i;
answer[1] = j;
return answer;
}
}
}
return answer;
}
}
728x90
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] 70. Climbing Stairs (0) | 2021.06.10 |
---|---|
[LeetCode] 322. Coin Change (1) | 2021.06.10 |
[LeetCode] 238. Product of Array Except Self (0) | 2021.06.06 |
[LeetCode] 217. Contains Duplicate (0) | 2021.06.06 |
[LeetCode] 121. Best Time to Buy and Sell Stock (0) | 2021.06.06 |