题解 | #找到满足条件的牛群组合#
找到满足条件的牛群组合
https://www.nowcoder.com/practice/8b9ba0f65fa0442b9808a24a18c6462d?tpId=354&tqId=10588483&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型二维数组
*/
public int[][] findThreeCows (int[] nums, int target) {
List<List<Integer>> res = threeSum(nums,target);
//将List<List<Integer>>类型转为int[][]
int n = res.size();
int[][] result = new int[n][3];
for(int i=0;i<n;i++){
for(int j=0;j<3;j++){
result[i][j] = res.get(i).get(j);
}
}
return result;
}
/** 简单的三数之和
*/
private static List<List<Integer>> threeSum(int[] nums, int target) {
ArrayList<List<Integer>> result = new ArrayList<>();
//排序方便计算
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
//去重
if (i == 0 || nums[i] != nums[i - 1]) {
//定义双指针
int l = i + 1, r = nums.length - 1;
while (r > l) {
int sum = nums[i] + nums[l] + nums[r];
if (sum > target) {
r--;
} else if (sum < target) {
l++;
} else {
result.add(Arrays.asList(nums[i], nums[l], nums[r]));
//去重
while (r > l && nums[l] == nums[++l]) {
}
while (r > l && nums[r] == nums[--r]) {
}
}
}
}
}
return result;
}
}
面试高频TOP202 文章被收录于专栏
面试高频TOP202题解
查看7道真题和解析