On May 27 2024, I encountered a daily Leetcode challenge entitled
Special Array With X Elements Greater Than or Equal X
This challenge is relatively easy and quite friendly for beginners to practice. Because I'm learning Golang, I implemented it using that language.
For the question link, you can go to the following page.
Solution
First of all, let's define the function.
func specialArray(nums []int) int {
}
Then, initiate the loop and associated dependent variables such as x and count into the function.
func specialArray(nums []int) int {
for i := 1; i <= len(nums); i++ {
x := i
count := 0
}
}
Next, loop back over the nums array to compare whether each element is greater than x, if yes, add it to the count variable.
for _, v := range nums {
if v >= x {
count++
}
}
Finally, check whether count is the same as x, if it is, immediately return x. However, if not, at the end of the function add return -1.
if count == x {
return x
}
Complete code:
func specialArray(nums []int) int {
for i := 1; i <= len(nums); i++ {
x := i
count := 0
for _, v := range nums {
if v >= x {
count++
}
}
if count == x {
return x
}
}
return -1
}
Top comments (0)