정수 배열 nums와 정수인 target이 주어진다.
nums에서 합산하면 target이 되는 두 숫자의 인덱스를 반환하라
각 입력에 정확히 하나의 솔루션이 있다고 가정 할 수 있으며 동일한 요소를 두 번 사용할 수 없습니다.
어떤 순서로든 답변을 반환 할 수 있습니다.
Constraints:
- 2 <= nums.length <= 103
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- 답은 하나만 존재한다.
Pseudocode (의사코드)
nums에서 더하면 target을 만드는 두 수를 구하라
target에서 0번요소를 뺀 값을 나머지 수에서 찾기
있다면 0과 해당하는 요소를 리턴
없다면 1번요소로 증가
...
반드시 한 가지 답이 존재하기 때문에 해결 할 수 있을 것이다.
답
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0; i<nums.length; i++)
{
int tempValue = target - nums[i];
for(int j=i+1; j < nums.length; j++)
{
if(tempValue == nums[j])
{
result = new int[]{i, j};
return result;
}
}
}
return result;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Two Sum.
Memory Usage: 38.8 MB, less than 97.05% of Java online submissions for Two Sum.
나중에 리팩토링을 해보자
출처
leetcode.com/problems/two-sum/
'Algorithm > LeetCode' 카테고리의 다른 글
HashMap Sorting in java (0) | 2021.03.18 |
---|---|
[LeetCode] Lemonade Change (1) | 2021.03.17 |
[LeetCode] Top K Frequent Elements (0) | 2021.03.15 |
[LeetCode] Roman to Integer (0) | 2021.03.12 |
[LeetCode] Path Sum Debuging (0) | 2021.03.11 |