【LeetCode解题一】Two Sum问题Java解答

来源:互联网 发布:一致性哈希 java实现 编辑:程序博客网 时间:2024/06/05 11:40

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, and you may not use the same element twice.

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

以上是问题,英文不难理解,即输入为一组整数和一个整数target,找到数组中两个相加等于target的数字的索引(即脚标),此题不难,用穷举便可解答

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

结果AC

今天是在LeetCode上刷题的第一天,希望自己能够坚持下去。

原创粉丝点击