문제
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]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
작성코드
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int leng = nums.Length;
int[] answer = new int[2];
for (int i = 0; i < leng; i++)
{
for (int k = i + 1; k < leng; k++)
{
if (nums[i]+nums[k] == target)
{
answer[0] = (i);
answer[1] = (k);
return answer;
}
}
}
return answer;
}
}
배운점
return null
보다는return Array.Empty<int>()
를 사용하는 것이 RunTime에 이득.nums.Length
를 변수에 담아 사용하는 것보다for
문 내에서 바로 사용하는 것이 RunTime이득.Count
보다Length
가 RunTime 이득.
'코테 > LeetCode' 카테고리의 다른 글
<LeetCode>14_Longest Common Prefix (0) | 2021.02.20 |
---|---|
<LeetCode>04_13_Roman To Integer (0) | 2021.02.09 |
<LeetCode>03_09_Palindrome Number (0) | 2021.02.09 |
<LeetCode>02_07_ReverseInteger (0) | 2021.02.09 |