LeetCode 刻意练习01--两数之和

两数之和

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

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

需求:
1.参数列表:给定整数数组nums和一个整数target
2.返回值:一个含有两个整数的数组

思路:
新建一个长度为2的数组,用于存储两个整数值。
在给定的数组里进行遍历,如果两个数的和为target,则将这两个数的角标存入到新建数组中

class Solution {
      public static int[] twoSum(int[] nums, int target) {
        int[] a = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            int j = i + 1;
            while (j < nums.length && nums[i] + nums[j] != target) {
                j++;
            }
            if (j < nums.length) {
                a[0] = i;
                a[1] = j;
            }
        }
        return a;
    }
}

在这里插入图片描述

发布了49 篇原创文章 · 获赞 2 · 访问量 897

猜你喜欢

转载自blog.csdn.net/qq_43720551/article/details/104598100
今日推荐