LeetCode - Problems - Algorithms - 35. Search Insert Position
Problem Description
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
My Solution (C#)
nums에 target을 insert한다고 가정 했을 때, insert 되는 위치를 return하는 문제.
nums는 오름차순으로 정렬되어있고, target 또한 오름차순에 맞게 insert 되어야 한다는 조건이 있다.
target이 nums 안에 이미 존재하고 있다면 해당 값의 index를 출력한다.
public class Solution {
public int SearchInsert(int[] nums, int target) {
for(int i = 0; i < nums.Length; i++)
{
if (nums[i] >= target)
{
return i;
}
}
return nums.Length;
}
}
- nums 배열을 모두 체크할 수 있도록 for 반복문을 이용했다. (index 값을 return 해야하므로)
- nums[i]가 target보다 크거나 같으면 해당 위치가 target이 위치한, 혹은 insert할 위치이므로 i 값을 return한다.
- 배열을 모두 확인했다면 모든 요소가 target보다 작다는 의미이므로 nums의 길이를 return한다.
'Problem solving > Algorithms' 카테고리의 다른 글
[LeetCode] 125. Same Tree (C#) (0) | 2024.01.12 |
---|---|
[LeetCode] 100. Valid Palindrome (C#) (0) | 2024.01.12 |
[LeetCode] 28. Implement strStr() (C#) (0) | 2021.02.02 |
[LeetCode] 27. Remove Element (C#) (0) | 2021.01.30 |
[LeetCode] 26. Remove Duplicates from Sorted Array (C#) (0) | 2021.01.29 |