반응형
Recent Posts
Notice
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- programmers
- Java
- recursion
- string
- two pointers
- priority queue
- binary tree
- 깊이우선탐색
- DP
- dfs
- 재귀함수
- ArrayList
- PCCP
- 브루트포스
- Array
- greedy
- leetcode
- Algorithm
- 리트코드
- coding
- hashset
- 부분배열
- 우선순위 큐
- HashMap
- 알고리즘
Archives
- Today
- Total
지식창고
[Java] LeetCode 540. Single Element in a Sorted Array 본문
728x90
반응형
[Java] LeetCode 540. Single Element in a Sorted Array
문 제 :
정렬된 정수 배열 nums가 주어진다.
nums 배열 안의 원소들은 한 숫자를 제외하고 모두 두 개씩 들어있다.
딱 하나만 들어있는 그 숫자를 구해라.
Constraint
{ 1 <= nums.length == 10^5 }
{ 0 == nums[i] <= 10^5 }
Example )
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
//////////////////////////////////////////////////////////
Input: nums = [3,3,7,7,10,11,11]
Output: 10
접 근 :
배열을 두 개씩 묶어서 검사한다.
해 결 :
배열을 두 개씩 보는데, 두 개가 같은 숫자면 pass이다.
만약 두 개가 같지 않다면, 처음 나온 숫자가 한 개만 있는 숫자이다.
만약 반복문을 끝까지 돌았는데도 함수종료가 되지 않았다면 맨 마지막 숫자가 하나만 있는 숫자라는 뜻이다.
결 과 :
class Solution {
public int singleNonDuplicate(int[] nums) {
int n = nums.length;
if(n == 1) return nums[0];
for(int i=0; i<n-1; i=i+2){
if(nums[i] != nums[i+1]) return nums[i];
}
return nums[n-1];
}
}728x90
반응형
'Algorithm > Leetcode' 카테고리의 다른 글
| [Java] LeetCode 1011. Capacity To Ship Packages Within D Days (0) | 2023.02.22 |
|---|---|
| [Java] LeetCode 122. Best Time to Buy and Sell Stock II (0) | 2023.02.21 |
| [Java] LeetCode 35. Search Insert Position (0) | 2023.02.20 |
| [Java] LeetCode 1162. As Far from Land as Possible (0) | 2023.02.10 |
| [Java] LeetCode 6. Zigzag Conversion (0) | 2023.02.03 |
Comments