数据结构 java 数组 输出一个数组中最小和第二小的数

思路:

如果单纯对数组排序,取前两个。可能数组的最小值数量很多,取不到第二小的数。

方法1:

时间复杂度: O(N)
辅助空间: O(1)

public class _test {
    static void print2Smallest(int arr[])
    {
        int first, second, arr_size = arr.length;

//        如果数组没有两个数,则返回错误
        if (arr_size < 2) {
            System.out.println(" 数组长度不够两位 ");
            return;
        }

        //初始化最小和第二小的数
        first = second = Integer.MAX_VALUE;
        for (int i = 0; i < arr_size; i++) {
// 如果当前元素小于最小元素first,则跟新first和second
            if (arr[i] < first) {
                second = first;
                first = arr[i];
            }

            /* 如果当前元素在first和second之间,更新second  */
            else if (arr[i] < second && arr[i] != first)
                second = arr[i];
        }
        //如果second是初始化的值,则没第二小的数
        if (second == Integer.MAX_VALUE)
            System.out.println("没有第二小的数");
        else
            System.out.println("最小的数是: "
                    + first
                    + " 第二小的数是:"+ second);
    }

    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int arr[] = { 12, 13, 1, 10, 34, 1 };
        print2Smallest(arr);
    }
}
/*This code is contributed by Devesh Agrawal*/


方法二:

时间复杂度: O(N)
辅助空间: O(1)

// Java program to find smallest and
// second smallest element in array
import java.io.*;
class GFG {
	public static void main(String args[])
	{
		int arr[] = { 12, 13, 1, 10, 34, 1 };
		int n = arr.length;
		int smallest = Integer.MAX_VALUE;
		// traversing the array to find
		// smallest element.
		for (int i = 0; i < n; i++) {
			if (arr[i] < smallest) {
				smallest = arr[i];
			}
		}
		System.out.println("smallest element is: "
						+ smallest);

		int second_smallest = Integer.MAX_VALUE;

		// traversing the array to find second smallest
		// element
		for (int i = 0; i < n; i++) {
			if (arr[i] < second_smallest
				&& arr[i] > smallest) {
				second_smallest = arr[i];
			}
		}
		System.out.println("second smallest element is: "
						+ second_smallest);
	}
}

// This code is contributed by Lovely Jain

你可能感兴趣的:(数据结构与算法,java,数据结构,算法)