计算一组整数的最大值和最小值----静态内部类的使用

面试应该不考这么简单的题吧

从控制台接收一组个数不定的整数的方法是百度出来的,感觉有些繁琐,无奈自己也没有更好的方法,欢迎告知

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 静态内部类的使用
 * @author Jenny
 *
 */
public class StaticInner {
	public static void main(String[] ar){
		System.out.println("请输入要比较的整数,以非整数结束:");
		ArrayList<Integer> a = new ArrayList<Integer>();
		boolean flag = true;
		while(flag){
			try{
			Scanner input = new Scanner(System.in);
			a.add(input.nextInt());
			}catch(Exception e){
				flag = false;
			}
		}
		Compare.Pair result = Compare.exe(a);
		System.out.println("**********result************");
		System.out.println("最大值为:"+result.max+"; 最小值为:"+result.min);
	}

}

class Compare{
	public static Pair exe(ArrayList<Integer> a){
		int ma = a.get(0);
		int mi = a.get(0);
		for(int i=1; i<a.size(); i++){
			if(a.get(i)>ma)
				ma = a.get(i);
			if(a.get(i)<mi)
				mi = a.get(i);
		}
		return new Pair(ma,mi);
	}
	
	static class Pair{
		public int max;
		public int min;
		Pair(int max, int min){
			this.max=max;
			this.min=min;
		}
	}
}


### 关于C/C++/Python 中一维数组最大值最小值交换的实现 #### 使用 Python 实现 在 Python 中可以利用列表解析以及内置函数 `max()` `min()` 来找到最大值及其索引位置,同样对于最小值也是如此。之后通过简单的赋值操作完成两者的互换。 ```python def swap_max_min(lst): if not lst: # 如果列表为空,则直接返回原列表 return [] min_val = min(lst) # 获取最小值 max_val = max(lst) # 获取最大值 min_idx = lst.index(min_val) # 找到最小值的位置 max_idx = lst.index(max_val) # 找到最大值的位置 # 创建一个新的列表来存储修改后的数据 result = list(lst) result[min_idx], result[max_idx] = result[max_idx], result[min_idx] return result # 测试例子 test_list = [3, 1, 4, 1, 5, 9, 2, 6] print(swap_max_min(test_list)) ``` 这段代码展示了如何在一个给定的一维整数列表里定位并交换其中的最大值最小值[^1]。 #### 使用 C++ 实现 当涉及到 C++ 编程语言时,可以通过遍历整个数组来找寻最大值最小值对应的下标,并最终执行它们之间的数值交换过程。 ```cpp #include <iostream> using namespace std; void swapMaxMin(int* arr, int size){ int minIndex=0; int maxIndex=0; for(int i=1 ;i<size;++i){ if(arr[i]<arr[minIndex]) minIndex=i; else if(arr[i]>arr[maxIndex]) maxIndex=i; } // Swap the minimum and maximum elements. int temp = arr[minIndex]; arr[minIndex]=arr[maxIndex]; arr[maxIndex]=temp; } // Function to display array content void showArray(const int *array,int length){ for(int idx=0;idx<length;++idx){ cout<<array[idx]<<" "; } cout<<"\n"; } ``` 此部分提供了完整的解决方案用于处理静态分配的一维整形数组,在该结构内寻找极值并对这些特定项实施置换动作[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值