Problem Description
Write a program to find a specific integer in a given integer array. The function has the following signature:
fun findNumber(arr: IntArray, target: Int): Boolean
The input arr
is an integer array, and target
is the integer we want to find.
If target
exists in the array, it should return true
, otherwise it should return false
.
Example
Input
arr = [1, 2, 3, 4, 5]
target = 3
Output
true
Input
arr = [1, 2, 3, 4, 5]
target = 6
Output
false
Solution Approach
To solve this problem, we need to search the array to check if the target number exists. There are several array search algorithms, but here we will use the most basic linear search.
By sequentially checking each element of the array, we return true
when the target number is found.
If we check all the way to the end of the array, we return false
. This approach has a time complexity of O(n), which increases with the length of the array.
However, if the array is sorted, we can use a binary search algorithm to reduce the time complexity to O(log n). For simplicity, we will implement linear search here.
Code Implementation
Now, let’s write code in Kotlin to solve this problem.
fun findNumber(arr: IntArray, target: Int): Boolean {
for (number in arr) {
if (number == target) {
return true
}
}
return false
}
Code Explanation
The code above runs a loop on all elements of the array arr
. It compares each element with target
, and if they are the same, it returns true
.
If target
is not found by the end of the loop, it returns false
.
Complexity Analysis
The time complexity of this algorithm is O(n). This is because the time taken to search increases proportional to the size n
of the array.
The space complexity is O(1) since no additional memory is used. This means it has optimal space complexity.
Test Cases
Additional Test Cases
val testArray = intArrayOf(10, 20, 30, 40, 50)
println(findNumber(testArray, 30)) // true
println(findNumber(testArray, 60)) // false
println(findNumber(intArrayOf(), 1)) // false
println(findNumber(intArrayOf(5), 5)) // true
println(findNumber(intArrayOf(5), 10)) // false
Conclusion
Through this example, we learned how to write a simple search algorithm using Kotlin. Linear search is the most basic rule of integration,
and it is important to choose the appropriate algorithm according to the amount of data and complexity in actual projects.
This helps develop the ability to solve various types of problems.