题解 | #寻找两头牛的情报关联#

寻找两头牛的情报关联

https://www.nowcoder.com/practice/5cb34321b6dd41bcbea3db454c2f6e9f

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param info int整型一维数组
     * @param target_weight int整型
     * @return int整型一维数组
     */
    public int[] findWeightRelation (int[] info, int target_weight) {
        // write code here
        int start = 0;
        int end = info.length - 1;
        while (start < end) {
            if (info[start] + info[end] > target_weight) {
                end--;
            } else if (info[start] + info[end] < target_weight) {
                start++;
            } else if (info[start] + info[end] == target_weight) {
                return new int[] {start + 1, end + 1};
            }
        }
        return new int[] {-1, -1};
    }
}

本题主要考察的知识点是双指针的应用,所用编程语言是java。

我们可以用双指针解决此题,首指针指向数组首端,尾指针指向数组末端。用start表示首指针,用end表示尾指针

如果info[start]+info[end]大于目标权重,则end--

如果info[start]+info[end]等于目标权重,则返回start+1和end+1

如果info[start]+info[end]小于目标权重,则start++

最后如果start在等于end之前都没有合适的组合则返回{-1,-1}

全部评论

相关推荐

三分入剑:我觉得还是学历问题 如果你真的想要进大厂不想在小厂的话读个211得研究生吧 我感觉简历还没你好呢 我都实习了俩月了 我投了一百多份能投出20多份简历 能面试六七次 我们部门只招研究生了都 现在连9本都很难找到像样的大厂了 你又没打过rm这种 我觉得想要进步的话就考个研究生吧
点赞 评论 收藏
分享
02-04 17:01
南昌大学 Java
牛客96763241...:拿插件直接投就完了,这玩意看运气的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务