twoSum

作者: 大湛湛 | 来源:发表于2017-03-21 13:30 被阅读16次

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。

你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。

注意事项

你可以假设只有一组答案。

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public static int[] twoSum(int[] numbers, int target) {
        // write your code here
        int[] arr = new int[2];
        for (int i = 0; i < numbers.length; i++){
            for (int j = i + 1; j < numbers.length; j++){
                if (numbers[i] + numbers[j] == target){
                    arr[0] = i + 1;
                    arr[1] = j + 1;
                }
            }
        }
        return arr;
    }
}

注意Checkstyl

相关文章

  • TwoSum

    题目大意: 找到数组中两个元素相加等于指定数的所有组合 情况一:给定数组中不含重复元素,且均为正整数 思路: 使用...

  • twoSum

    Problem Given an array of integers, return indices of the...

  • TwoSum

    刷题当然要从TwoSum开始了~~python刷题果然容易~~~class Solution(object):de...

  • TwoSum

    介绍:Two Sum给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数 twoSum 返回这两个相...

  • TwoSum

  • TwoSum

    Problem### Given an array of integers, find two numbers s...

  • TwoSum

    简单方法,两边循环,一个推着另一个,复杂度n2 使用map,检查过的存起来map,每拿到一个新的,就去map里查,...

  • TwoSum

    题目描述: Given an array of integers, return indices of the t...

  • twoSum

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需要返回这两个...

  • TwoSum

    暴力暴力算法时间复杂度O(n²),空间复杂度O(1) 两次遍历 HashMap时间复杂度:O(n),我们把包含有 ...

网友评论

    本文标题:twoSum

    本文链接:https://www.haomeiwen.com/subject/kefgnttx.html