力扣第7刷-两数之和

简介: 力扣第7刷-两数之和

Example 7

两数之和

题目概述:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6

输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6

输出:[0,1]

解题思路:枚举数组中的每一个数 x,寻找数组中其他位置是否存在 target - x。

在使用遍历整个数组的方式寻找 target - x 时,需要注意每一个位于 x 之前的元素都已经和 x 匹配过,因此不需要再进行匹配。而每一个元素不能被使用两次,所以只需要在 x 后面的元素中寻找 target - x。

解题步骤:

1. 定义变量记录数组长度。

2. 定义外部for循环,从0索引位置开始遍历,作为x(两数的第一个数)。

3. 定义内部for循环,遍历x之后的元素,作为target - x(两数的第二个数),判断两数之和是否为target,若相等,则将两数的索引放入新数组内返回,否则继续循环遍历,直至找到符合条件的两数或循环结束,若循环结束仍没有找到符合条件的两数,则说明没有可行的情况,返回长度为0的数组。

 

示例代码如下:

public class SumOfTwoNumbers {

   /**

    * 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

    * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    * 你可以按任意顺序返回答案。

    * 示例 1:

    * 输入:nums = [2,7,11,15], target = 9

    * 输出:[0,1]

    * 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

    * 示例 2:

    * 输入:nums = [3,2,4], target = 6

    * 输出:[1,2]

    * 示例 3:

    * 输入:nums = [3,3], target = 6

    * 输出:[0,1]

    * 来源:力扣(LeetCode)

    * 链接:https://leetcode.cn/problems/two-sum

    */

   public static void main(String[] args) {

       int[] nums = {2, 7, 11, 15};

       SumOfTwoNumbers sotn = new SumOfTwoNumbers();

       System.out.println(sotn.twoSum(nums, 9));

   }

 

   /**

    * 个人

    * @param nums

    * @param target

    * @return

    */

/*    public int[] twoSum(int[] nums, int target) {

       int[] targetNums = new int[2];

       int arrayLength = nums.length;

       for (int i = 0; i < arrayLength; i++) {

           for (int j = i + 1; j < arrayLength; j++) {

               if (nums[i] + nums[j] == target) {

                   targetNums[0] = i;

                   targetNums[1] = j;

                   return targetNums;

               }

           }

       }

       return null;

   }*/

 

   /**

    * 官方

    *

    * @param nums

    * @param target

    * @return

    */

   public int[] twoSum(int[] nums, int target) {

       int n = nums.length;

       for (int i = 0; i < n; ++i) {

           for (int j = i + 1; j < n; ++j) {

               if (nums[i] + nums[j] == target) {

                   return new int[]{i, j};

               }

           }

       }

       return new int[0];

   }

 

}

相关文章
|
7月前
|
存储
|
11月前
|
存储 C++ 容器
两数之和(力扣刷题)
两数之和(力扣刷题)
|
11月前
四数之和(力扣刷题)
四数之和(力扣刷题)
刷 leetcode三个数的最大乘积 | 刷题打卡
刷 leetcode三个数的最大乘积 | 刷题打卡
62 0
|
存储 算法 Java
力扣LeetCode初级算法(加一,移动零)
力扣LeetCode初级算法(加一,移动零)
105 0
|
存储 算法
【刷算法】LeetCode- 两数之和
【刷算法】LeetCode- 两数之和