본문 바로가기
코테노트/Blind 75 LeetCode Questions

(1) Two Sum of Blind 75 LeetCode Questions

by 테크한스 2022. 11. 7.

이번에는 코딩테스트 문제를

leetcode 에서 나오는 핵심적인 묶음 문제인

Blind 75 LeetCode Questions 중에서

75개를 순서대로 풀어볼 예정이다.

사용언어는 JAVA 이다

 

https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions

 

Blind 75 LeetCode Questions - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

(1) Two Sum 

 

이 문제는 언제나 수학의 정석처럼 집합챕터에 있는 내용일 수도 있겠다.

책자의 맨앞에 페이지들 (항상 까맣다)

 

코딩에 솔루션(문제해결)도 중요하지만 효율(efficiency)이 더 중요할 수도 있겠다

그러나 동기부여와 스킬셋 향상을 위해서는 

솔루션이든 무엇이든 부둥켜 안고 있어야 한다.

 

여러가지 중 나는 아래와 같은 고전적인 답을 내놓는다

 

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

Example 2:

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

Example 3:

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

 

 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 아까 답은 항상 2개 니까 array 를 미리 만들어줄께요
        int [] answer = new int [2];

        // nums가 입력되는 array인까요 받아서 
        // nums 와 nums + 1을 해서 2개를 비교하면 되겠죠
        for(int i=0;i<nums.length;i++){
            // 하나만 비교 할 수 없기에 중첩 for문으로 한번더 돌립니다. +1 해서
            for(int j=i+1;j<nums.length;j++){
                // 여기서 답을 걸러줍니다. 조건은?
                if(nums[i] + nums[j] == target){
                    // 답이 2개라고 했으니 array에 하나씩 넣어요
                    answer[0] = i;
                    answer[1] = j;
                }
            }
        }
        // 답을 리턴
        return answer;
    }
}

 

 

댓글