leetcode记录1

    xiaoxiao2022-06-23  15

    这是一道soeasy的题目

    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.

    给一个数组和目标值,数组中的两个数相加是目标值,返回值是数组中的下标,题中给出一个例子

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

    直接上代码就好啦,两循环就会解决:

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

    转载请注明原文地址: https://ju.6miu.com/read-1123255.html

    最新回复(0)