sean.jin
Spark Code Blog
sean.jin
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발공부
      • Kotlin
      • LeetCode
      • Algorithm
      • React
    • 주식차트
    • 책리뷰
    • 유틸리티

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 주식입문자
  • 변동성
  • 책추천
  • 주식책리뷰
  • 부의 추월차선
  • 초보
  • 아빠와 딸의 주식투자 레슨
  • 쿼드러플위칭데이
  • 책리뷰
  • 주식투자
  • 오
  • 경제
  • 자기개발
  • 트리플 위칭데이
  • 책
  • 네마녀의날

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
sean.jin

Spark Code Blog

[Kotlin] LeetCode 1. Two Sum 풀이 - for index, indices 활용
개발공부/LeetCode

[Kotlin] LeetCode 1. Two Sum 풀이 - for index, indices 활용

2021. 6. 4. 10:51
반응형

문제

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.

예시

  • 위와같이 nums와 target이 fun twoSum에 들어가서 반환값이 0,1이 나와야하게 만들어야합니다. 
  • 0,1은 nums의 index(위치) 값이고 둘의 합은 9가 되어야합니다. 
  • 둘의 합이 9가되는 두 숫자의 index를 찾아서 intArray로 반환이 목표입니다.

풀이

class Solution {
   fun twoSum(nums: IntArray, target: Int): IntArray? {
   //반복구성
    for (i in nums.indices) { //nums.indices는 0..nums의 array사이즈까지 range를 뜻합니다.
        for (j in i + 1 until nums.size) {//i+1은 같은값을 반복시키지 않기위해 더해주고 num의 사이즈까지 반복합니다.
   //타겟과 같은 값 찾기
            if (nums[j] == target - nums[i]) { //nums[i]는 i에 위치한 nums를 의미합니다.
                return intArrayOf(i, j) // 같다면 index인 i와 j를 리턴합니다
            }
        }
    }
    throw IllegalArgumentException("No two sum solution") //만약 아무것도 충족시키지 못할경우 
    }
}

결과

 

반응형

'개발공부 > LeetCode' 카테고리의 다른 글

[Kotlin] LeetCode: Intersection of Two Arrays IISolution 풀이  (0) 2021.06.11
[Kotlin] Array 에 같은 숫자 찾기, HashMap활용 풀이 - LeetCode: Single Number  (0) 2021.06.10
[Kotlin] Array에 반복되는 아이템 삭제하기 - ArrayList distinct - LeetCode: Contains Duplicate - 풀이 과정  (0) 2021.06.08
[Kotlin] LeetCode - Best Time to Buy and Sell Stock IISolution - 풀이과정  (0) 2021.06.05
[Kotlin] String, Int 순서 뒤집기 - LeetCode: Reverse Integer 풀이  (0) 2021.06.05
    '개발공부/LeetCode' 카테고리의 다른 글
    • [Kotlin] Array 에 같은 숫자 찾기, HashMap활용 풀이 - LeetCode: Single Number
    • [Kotlin] Array에 반복되는 아이템 삭제하기 - ArrayList distinct - LeetCode: Contains Duplicate - 풀이 과정
    • [Kotlin] LeetCode - Best Time to Buy and Sell Stock IISolution - 풀이과정
    • [Kotlin] String, Int 순서 뒤집기 - LeetCode: Reverse Integer 풀이
    sean.jin
    sean.jin
    앱개발, 알고리즘, JS, Kotlin, 미국 취업준비

    티스토리툴바