给一个数组array,一个目标值target,找到数组中两个数相加,小于目标值大最大和并输出,没有则输出-1 Bertha 。 2022-08-28 15:54 96阅读 0赞 public class test12 { public static void main(String[] args) { System.out.println(TwoSum(new int[]{34,23,1,25,75,33,54,8},60)); } public static int TwoSum(int[] L, int K){ //参数校验 int result = -1; if(L == null || L.length<=0){ return result; } int[] num =Arrays.stream(L).sorted().toArray(); if(num[0]>K){ return result; } //有序数组 int left = 0; int right = num.length-1; while (left<right){ if(num[left]+num[right]<K){ result = Math.max(result,num[left]+num[right]); left++; } if(num[left]+num[right]>=K){ right --; } } return result; } }
还没有评论,来说两句吧...