[LeetCode / Easy] 1. Two-Sum (Java)

이하얀·2025년 1월 21일
0

📙 LeetCode

목록 보기
1/13

💬 Info



Problem

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].

예시 2

  • Input: nums = [3,2,4], target = 6
  • Output: [1,2]

예시 3

  • Input: nums = [3,3], target = 6
  • Output: [0,1]


Constraints

  • 2<=nums.length<=1042 <= nums.length <= 10^4
  • 109<=nums[i]<=109-10^9 <= nums[i] <= 10^9
  • 109<=target<=109-10^9 <= target <= 10^9
  • Only one valid answer exists


문제 이해

  • 배열로 주어진 두 숫자의 합이 target이 경우의 index들을 반환하는 문제


알고리즘

풀이 시간 : 7분

  • 두 수의 합이 타겟 값과 일치하는지를 지속적으로 확인
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i < nums.length -1; i++){
            for(int j = i+1; j < nums.length; j++){
                if(nums[i] + nums[j] == target)
                    return new int[]{i, j};
            }
        }
        return new int[]{};
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글