본문 바로가기

Programming/알고리즘 공부

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

 

여기 주어진 정수 배열 nums와 정수 target이 있다.

정수 배열 nums의 인덱스 값의 합이 target과 동일한 경우 해당 인덱스 값을 리턴하시오.


예시

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

배열 nums의 0번, 1번 인덱스 값은 각각 2, 7이며, 이 둘의 합은 target의 값인 9와 동일하다.

따라서 인덱스 0, 1을 반환.


답안

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
        int[] result = new int[2];
      
         for(int i = 0; i<nums.length; i++){
            for(int j = i+1; j<nums.length; j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    break;
                }
            }
        }
        return result;
    }
}

 

class Solution {
  public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
      if (map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) {
        result[0] = i;
        result[1] = map.get(target - nums[i]);
        break;
      }
      map.put(nums[i], i);
    }
    return result;
  }
}
반응형