[LeetCode] 1.TwoSum

2020. 12. 28. 16:31

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

1.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] Output: 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]

 

Constraints:

  • 2 <= nums.length <= 103
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

 

2.Code

package leetCode;

public class TwoSum {

	public static void main(String[] args) {		
		int[] test = {3, 7, 11, 15};
		int target = 9;
		int[] result = twoSum(test, target);
	}
    
    public static 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[i] + nums[j] == target) {
                    int[] Output = {i,j};
                    return Output;
                }
            }
        }
        return null;
    }
}

 

3. Report

중복해서 더할 필요가 없는데 j=0부터 시작해서 이상하게 풀었었다;ㅁ;

 

4.Learned

- 배열

'Algorithm > 문제' 카테고리의 다른 글

[LeetCode] 6.Merge Two SortedLists  (0) 2020.12.30
[LeetCode] 5.Palindrome Number  (0) 2020.12.29
[LeetCode] 4.Reverse Integer  (0) 2020.12.28
[LeetCode] 3.Roman to Integer  (0) 2020.12.28
[LeetCode] 2.Add Two Numbers  (0) 2020.12.28

BELATED ARTICLES

more