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

时间:2022-06-07
本文章向大家介绍BAT面试算法进阶(1)-两个数求和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

英文题目:

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://leetcode.com/problems/two-sum/description/