Java数组--求一个数组中连续m个数的和最大的数组组合
一个数组中有n个整数,找出连续的m个数加和是最大的组合,打印出来.
在实现此功能的过程中主要使用System.arrayCopy方法:
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
将指定源数组(src)中的数组从指定位置(srcPos)复制到目标数组(dest)的指定位置(destPos到destPos+length)。
1 public class MaxArray { 2 public static void main(String[] args) { 3 // int[]数组,asList返回int[]; 4 Integer[] paras = { 133, 445, 6768, 23, 656, 123105, 768, 234, 5 787, 6321, 5677, 234, 1445, 3551, 547, 3245, 12357 }; 6 //引用类型的数组转化为集合 7 // List<Integer> lists = Arrays.asList(paras); 8 int m = 6; 9 //将集合转化成数组 10 // System.out.println(getArray((Integer[]) lists.toArray(),n)); 11 System.out.println(getArray(paras,m)); 12 } 13 14 /** 15 * 求出数组中连续m个数的和最大 16 * @param params 17 * @param m 18 * @param <T> 19 * @return 20 */ 21 public static <T> String getArray(Integer[] params,int m){ 22 //声明maxs,初始化temp 23 Integer[] maxs = null,temp = null; 24 if (!(params instanceof Integer[])){ 25 return "参数类型错误!"; 26 } 27 //临时数组,用于循环数组用 28 temp = new Integer[m]; 29 //存放和最大的数组 30 maxs = new Integer[m]; 31 int len = params.length; 32 for (int i=0;i<len;i++){ 33 //连续个m数需在数组内有效 34 if (i+m<=len){ 35 //数组复制,相当于切片 36 /** 37 * arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 38 * 将指定源数组(src)中的数组从指定位置(srcPos)复制到目标数组(dest)的指定位置(destPos到destPos+length)。 39 */ 40 System.arraycopy(params,i,temp,0,m); 41 if (maxs[0] == null || (maxs[0]!=null && (getSum(maxs)<getSum(temp)))){ 42 //引用相同,不可使用maxs = temp 43 //从temp复制一份给maxs 44 System.arraycopy(temp,0,maxs,0,m); 45 } 46 } 47 } 48 //将数组以字符打印 49 return Arrays.toString(maxs); 50 } 51 52 //取数组或者集合的加和 53 public static <T> int getSum(T t){ 54 int sum = 0; 55 //对list集合的操作 56 if (t instanceof List<?>){ 57 List<?> temp = (List<?>) t; 58 int len = temp.size(); 59 for (int i = 0;i<len;i++){ 60 sum += (Integer) temp.get(i); 61 } 62 }else if (t instanceof Integer[]){//对数组的操作 63 Integer[] temp = (Integer[])t; 64 //求出数组的和 65 for (int i=0;i<temp.length;i++){ 66 sum += temp[i]; 67 } 68 } 69 return sum; 70 } 71 }
分类:
Java算法
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库