LeetCode - twoSum

dropKick·2020년 7월 10일
0

코딩테스트

목록 보기
8/17

풀이

  • 배열을 탐색해서 두 수를 더하는 간단한 문제

코드

public int[] twoSum(int[] nums, int target) {
        int j;
        for (int i = 0; i < nums.length; i++) {
        for ( j = i + 1; j < nums.length; j++) {
            if(nums[j] == target - nums[i]){
                return new int[]{i,j};
           }
        }
     }
    throw new IllegalArgumentException("");
  }
  • 굳이 변수를 할당해야할까 싶어 그냥 하다가 return 할게 없어서 급하게 예외 추가
  • for 루프를 두 번 돌았으니 O(N2)O(N^2) 시간복잡도로 버블 정렬하고 동일

0개의 댓글