leetcode(1)——两数之和

leetcode第一题:两数之和

题目描述:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9,所以返回 [0, 1]

解答过程:

根据题意,数组中一定会有一个答案,于是我首先想到的是用目标值target减去数组nums中的某个数得出差值,再到数组剩下的数中查找等于差值的数即可。

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

执行结果:通过

执行用时:50 ms, 在所有 Java 提交中击败了48.01%的用户

内存消耗:39.9 MB, 在所有 Java 提交中击败了53.44%的用户

猜你喜欢

转载自blog.csdn.net/keepfriend/article/details/107872750