SOFTWARE/ALGORITHM
[leetcode] two sum
eooa
2021. 10. 8. 16:53
반응형
네.. 게으르지만 꾸준히 배우고 싶은 글쓴이입니다.
잘 못하는 코딩이지만, 계속하고 싶은 접니다.
오늘은 leetcode에 가입을 하고, 첫 알고리즘 문제를 풀어 본 경험을 공유합니다.
일단 저는, 비기너이기 때문에..
얼마만큼의 효율적인 코드냐 보다는,
제가 이 문제를 해결하느냐 못하느냐에 중점을 두기로 했습니다.
two sum은 easy 난이도인데..
저는 제법 시간을 많이 썼다는..^^
이것도 계속하면 나아지겠죠?
문제는 이겁니다.
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] Output: 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 <= 109Only one valid answer exists.
랜덤으로 주어진 array와, target이 있습니다.
array안의 두 숫자를 더해서 target과 같은 값이 나오게 하려면,
어떻게 해야 할까요?
나의 해결책은 이러했다.
다른 난다 긴다 한 사람들의 좋은 코드가 많겠지만,
나의 실력은 현재 이 정도..
class Solution {
public int[] twoSum(int[] nums, int target) {
//결과를 담을 array 생성
int[] result = new int[2];
//for문으로 array안의 숫자들을 꺼내볼 예정
for(int i=0; i<nums.length; i++){
//for문을 한번 더 돌려서, 두개의 숫자를 비교
for(int j=0; j<nums.length; j++){
//두 숫자의 합이 같고, i와j가 같은숫자가 아닐때
if(nums[i]+nums[j] == target && i!=j){
//결과array의 인덱스에 차차 담아줌
//j가 앞의 숫자, i가 뒤의 숫자
//j가 안쪽 for문에 있기 때문.
result[0] = j;
result[1] = i;
}
}
}
return result;
}
}
아래는 성공 인증샷!

반응형