LeetCode 알고리즘 문제풀이

[LeetCode-1] Two Sum 문제풀이 - Java 사용

줄라이퍼스트 2020. 9. 21. 20:55

Two Sum 문제풀이 - Java 사용

구글번역기를 이용하여 번역

nums배열과 target을 주어지면 target에 해당하는 합한 값을 ouput하는 문제

ex)  nums[2,7,11,15], target = 9 이면 nums[0]과 nums[1] 번째에있는 2 + 7로 계산

class Solution {
   public int[] twoSum(int[] nums, int target) {

		Map<Integer, Integer> map = new HashMap<>();
       
		try {
			for (int i = 0; i < nums.length; i++) {

				int tmp = target - nums[i];
				// 1, target = 9, nums[0] = 2; -> 7 // 2, target = 9, nums[1] = 7; -> 2,
                // key와 대응되는 value값을 불러올 때
				if (map.containsKey(tmp)) { 
					return new int[] { map.get(tmp), i };
				}
                // map 저장
				map.put(nums[i], i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nums;
	}
}