본문 바로가기

Algorithms/LeetCode

[Java] LeetCode 문제 풀이 : Problem1 Two Sum (Array)

---문제---

 

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.

 

interger 로 구성된 배열 nums 와 interger 숫자 target 이 주어졌을 때,
nums 에  포함된 숫자들 중 더해서 target 숫자가 될 수 있는 숫자 2개의 index를 반환하는 코드를 짜시오. 

각 문제마다 정확히 1가지의 해답만 가지며 같은 중복되는 숫자는 없다는 것을 가정합니다.

어떤 순서로라도 반환할 수 있습니다.

 

 

---코드---

 

public class Leet1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] nums = {2,7,1,2};
		int target = 9;
		
		int[] answer = twoSum(nums,target);

	}
	
	public static int[] twoSum(int[] nums, int target) {
        int[] temp=new int[2];
        for(int i=0; i<nums.length-1; ++i){
            for(int j=i+1; j<nums.length; ++j){
                if(nums[i]+nums[j]==target){
                    temp[0]=i;
                    temp[1]=j;
                    return temp;    
                }
                 
            }
        }
        
        return temp;
    }

}

 

---결과---

 

 

---출처---

leetcode.com/problems/two-sum/

 

반응형