每日一题【20220411】

题目

Find the smallest and second smallest elements in an array(查找数组中第二小的元素)

Difficulty Level : Basic

Find the smallest and second smallest elements in an array.

Example:

1
2
3
Input:  arr[] = {12, 13, 1, 10, 34, 1}
Output: The smallest element is 1 and
second Smallest element is 10

解题思路

A Simple Solution is to sort the array in increasing order. The first two elements in sorted array would be two smallest elements. Time complexity of this solution is O(n Log n).
A Better Solution is to scan the array twice. In first traversal find the minimum element. Let this element be x. In second traversal, find the smallest element greater than x. Time complexity of this solution is O(n).
The above solution requires two traversals of input array.
An Efficient Solution can find the minimum two elements in one traversal. Below is complete algorithm.
Algorithm:

1
2
3
4
5
6
7
1) Initialize both first and second smallest as INT_MAX
first = second = INT_MAX
2) Loop through all the elements.
a) If the current element is smaller than first, then update first
and second.
b) Else if the current element is smaller than second then update
second

Implementation:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// C program to find smallest and second smallest elements
#include <stdio.h>
#include <limits.h> /* For INT_MAX */

void print2Smallest(int arr[], int arr_size)
{
int i, first, second;

/* There should be atleast two elements */
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}

first = second = INT_MAX;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] < first)
{
second = first;
first = arr[i];
}

/* If arr[i] is in between first and second
then update second */
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == INT_MAX)
printf("There is no second smallest element\n");
else
printf("The smallest element is %d and second "
"Smallest element is %d\n", first, second);
}

/* Driver program to test above function */
int main()
{
int arr[] = {12, 13, 1, 10, 34, 1};
int n = sizeof(arr)/sizeof(arr[0]);
print2Smallest(arr, n);
return 0;
}

Output :

1
The smallest element is 1 and second Smallest element is 10

The same approach can be used to find the largest and second largest elements in an array.
Time Complexity: O(n)

  • 稳健!

image-20220412175611174

参考资料