首页 > 其他 > 详细

LeetCode01.Tow Sum

时间:2021-01-22 00:00:56      阅读:32      评论:0      收藏:0      [点我收藏+]

1.Tow Sum

Description:Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]

Example 2:

Input: nums = [3,2,4], target = 6 Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6 Output: [0,1]

Constraints:

Input: nums = [3,2,4], target = 6
Output: [1,2]In
put: nums = [3,2,4], target = 6
Output: [1,2]

Java:

这里我们最容易想到的就是暴力破解的方法,遍历整个数组,找到相加为target的两个数字,返回他们的数组索引,当然要保证他们只被使用过一次哦~

public class Solution {
    public static int[] towSum(int[] nums, int target) {
        int[] res = 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) {
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;
    }

LeetCode01.Tow Sum

原文:https://www.cnblogs.com/shangguankai198603/p/14311022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!