分享

BAT面试算法进阶(1)-两个数求和

 长沙7喜 2018-08-19

英文题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:


Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].


中文译文:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]


解决思路:

    1.第一层循环:遍历数组nums, 按顺序获取元素 nums[i];

    2.第二层循环:遍历数组nums,从i后面的位置遍历

    3.判断如果i位置上的元素+j位置上的元素 值的和 等于target 则表示找到了位置.否则继续遍历循环.直到数组遍历完成


C语言答案:


python语言答案:


题目源地址: https:///problems/two-sum/description/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多