zoukankan      html  css  js  c++  java
  • leetcode算法-两数之和

    一、题目

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

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

    示例:

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

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

    二、解题思路

    两层循环,每次两个值组合,只要由两个数相加,等于target直接return即可

    三、代码

     public int[] twoSum(int[] nums, int target) {
            int[] array = new int[2];
            for(int i = 0;i < nums.length - 1;i++){
                for(int j = i+1;j < nums.length;j++){
                    if(nums[i] + nums[j] == target){
                        array[0] = i;
                        array[1] = j;
                        return array;
                    }
                }
            }
            return array;
        }
  • 相关阅读:
    /etc/fstab 文件解释
    CRLF和LF
    Git远程操作详解
    jsp错误处理
    jsp隐式对象
    关于循环队列要注意的
    JSP动作元素
    JSP指令
    jsp语法简介
    jsp声明周期
  • 原文地址:https://www.cnblogs.com/mcjhcnblogs/p/13138086.html
Copyright © 2011-2022 走看看