题解 | #找到满足条件的牛群组合#

找到满足条件的牛群组合

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题解

全部评论

相关推荐

想顺利毕业的猕猴桃在看牛客:好几个月没面试了,腾讯留面评吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务