题目考察的知识点
考察双指针应用
题目解答方法的文字分析
与题目 https://www.nowcoder.com/practice/42ae88bedeb74da99813f6150769d07e 类似,数组排序后使用左右指针分别从首尾进行遍历,求和与target比较,注意去重操作。具体看代码实现即可
本题解析所用的编程语言
使用Java解答
完整且正确的编程代码
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型二维数组 */ public int[][] findThreeCows (int[] nums, int target) { // write code here List<List<Integer>> res = new ArrayList(); int len = nums.length; if(nums == null || len < 3) return new int[][]{}; Arrays.sort(nums); // 排序 for (int i = 0; i < len ; i++) { if(i > 0 && nums[i] == nums[i-1]) continue; // 去重 int L = i+1; int R = len-1; while(L < R){ int sum = nums[i] + nums[L] + nums[R]; if(sum == target){ res.add(Arrays.asList(nums[i],nums[L],nums[R])); while (L<R && nums[L] == nums[L+1]) L++; // 去重 while (L<R && nums[R] == nums[R-1]) R--; // 去重 L++; R--; } else if (sum < target) L++; else if (sum > target) R--; } } int[][] ret = new int[res.size()][res.get(0).size()]; for(int i=0; i<res.size(); i++){ for(int j=0; j<res.get(0).size(); j++){ ret[i][j] = res.get(i).get(j); } } return ret; } }