Last active
January 12, 2021 02:02
-
-
Save mumunuu/2f56ba022caf84ee26d9ce1e7aa1ed3e to your computer and use it in GitHub Desktop.
algorithm(leetcode) Single Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func singleNumber(nums []int) int { | |
if len(nums) == 1 { //요소가 1개인 배열은 종료. | |
return nums[0] | |
} | |
sort.Ints(nums) //정렬하면 0번째 인덱스와 1번째 인덱스는 같은 값을 갖는다. | |
for i := 0; i+1 < len(nums); i = i + 2 { | |
//정렬된 배열의 현재 요소와 다음 요소가 맞지 않으면 현재 인덱스가 정답. | |
if nums[i] != nums[i+1] { | |
return nums[i] | |
} | |
} | |
// for 문 이내로 맞추지 못하면 마지막 요소가 정답. | |
return nums[len(nums)-1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment