728x90
반응형
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].
아주 Easy한 문제지만.. 왜 생각보다 오랜만에 할려니깐 잘 안풀렸다.
a, b 를 따로 설정해준 건 이제 두 개의 output 이 나와야하니깐 그리고 그거에 대한 sum 을 해주니깐 그렇게 했다
--- 사실... a, b 설정 안해줘도 괜찮았을 듯..
이중 포문이었으며 그 안에 들어가는 범위가 좀 중요하게 됬다. j 그 후자는 이제 i+1 부터 nums.length 까지 돈다는 거가 핵심.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
int sum=0;
int a=0;
int b=0;
for(int i =0;i<nums.length;i++){
a=nums[i];
for(int j=i+1; j<nums.length; j++){
b=nums[j];
//System.out.println(b);
if(a+b == target)
{
result[0]=i;
result[1]=j;
System.out.println(result[0]+"+"+result[1]);
//이중일 경우에 break loop
return result;
}
}
}
return result;
}
}
728x90
반응형