律所网站建设建议,vr成品网站源码在线观看,wordpress 对象存储,泉州模板建站源码万物惊鸿#xff0c;唯我澄明 —— 24.3.9 1. 两数之和https://leetcode.cn/problems/two-sum/ 给定一个整数数组 nums 和一个整数目标值 target#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数#xff0c;并返回它们的数组下标。 你可以假设每种输入只会… 万物惊鸿唯我澄明 —— 24.3.9 1. 两数之和https://leetcode.cn/problems/two-sum/ 给定一个整数数组 nums 和一个整数目标值 target请你在该数组中找出 和为目标值 target 的那 两个 整数并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。 暴力枚举 思路及算法 对数组进行遍历对数组中每一个值都进行二次遍历二分查找遍历寻找有没有和他相加和为目标值的数如果有则返回两数的下标如果没有则进行下一个数的遍历 最容易想到的方法是枚举数组中的每一个数 x寻找数组中是否存在 target - x。 当我们使用遍历整个数组的方式寻找 target - x 时需要注意到每一个位于 x 之前的元素都已经和 x 匹配过因此不需要再进行匹配。而每一个元素不能被使用两次所以我们只需要在 x 后面的元素中寻找 target - x。 链接https://leetcode.cn/problems/two-sum/solutions/434597/liang-shu-zhi-he-by-leetcode-solution/ 来源力扣LeetCode class Solution {public int[] twoSum(int[] nums, int target) {for(int i0;inums.length;i){for(int j i1;jnums.length;j){if(nums[i]nums[j]target){return new int[]{i,j};}}}return new int[0];}
}