当前位置: 移动技术网 > IT编程>开发语言>Java > leetcode No1. 两数之和

leetcode No1. 两数之和

2020年07月07日  | 移动技术网IT编程  | 我要评论

题目链接:https://leetcode-cn.com/problems/two-sum/

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

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

示例:

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

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

方法一:暴力法

暴力法很简单,遍历每个元素 xx,并查找是否存在一个值与 target - xtarget−x 相等的目标元素。

package twosum;

class Solution1 {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    public static void main(String[] args) {
        Solution1 solution=new Solution1();
        int[] nums={2,7,11,1

本文地址:https://blog.csdn.net/jxq0816/article/details/107133542

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网