数据结构 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值