leetcode记录1

来源:互联网 发布:java字符串升序排列 编辑:程序博客网 时间:2024/06/05 19:44

这是一道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;    }}


0 0
原创粉丝点击