본문 바로가기
Algoritm/Quiz-Solutions

[Leetcode 1] two Sum

by 💜autumn 2020. 8. 2.

1) Question

https://leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

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

 

2) My Solution

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

 

3) Solution

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

 

4) Check Point!

  - break문은 한 블럭만 깰 수있다!

  - 반복문을 깨는것을 굳이 할 필요없다 >> 오히려 시간소모가 더 되는 경우 존재! >> Tip! 바로 return하면 OK!

  - 조건/반복문 안에서 return하는 경우 예외처리 필수 

     → throw new IllegalArgumentException("there is no Solution.");

 

댓글