`
zeyuphoenix
  • 浏览: 59839 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

收集面试题(一)(取得数组最大最小值)

阅读更多
取得一个数组的最大值和次最大值:

public static void main(String[] args) {
		int[] nums = { 2, 3, 4, 1, 2 };
		System.out.println(getMax(nums));
		System.out.println(getPerMax(nums));
	}

	public static int getMax(int[] nums) {

		int max = Integer.MIN_VALUE;
		if (nums == null || nums.length == 0) {
			throw new NullPointerException(
					"the array is null or length less than 1");
		}

		max = nums[0];

		for (int i = 1; i < nums.length; i++) {

			if (nums[i] > max)
				max = nums[i];
		}

		return max;
	}

	public static int getPerMax(int[] nums) {

		int max = Integer.MIN_VALUE;
		int perMax = Integer.MIN_VALUE;

		if (nums == null || nums.length < 2) {
			throw new NullPointerException(
					"the array is null or length less than 2");
		}
		max = nums[0];
		for (int i = 1; i < nums.length; i++) {

			if (nums[i] > max)
				max = nums[i];
		}

		for (int i = 0; i < nums.length; i++) {
			if (nums[i] > perMax && nums[i] < max) {
				perMax = nums[i];
			}
		}
		if (max == perMax)
			throw new RuntimeException("no secord number.");
		return perMax;
	}


分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics