LeetCode 1 - Two Sum

[Java] Leetcode 1 - Two Sum

Two Sum

  • 나의 답:

    class Solution {
      public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i <nums.length; i++){
          for(int j = nums.length-1; j > i;j--){
    // j는 i보다 클 때 까지만 반복되도록 설정했다. 어차피 이전 인덱스는 계산을 마쳤기 때문에.
            int sum = nums[i]+nums[j];
            if(sum == target){
              return new int[]{i,j};
            }
          }
        }
        return new int[] {0,0};
      }
    }
    
  • 다른 사람들의 답을 보면, HashMap을 사용한 사람도 있던데, 그 방법도 한 번 고안해봐야할 것 같다.
  • 결과: 결과