两数之和(简单)

Posted kanhin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两数之和(简单)相关的知识,希望对你有一定的参考价值。

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

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

给出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].

这道题也是很简单:遍历一下就好

Java版

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

  

两层for循环感觉不大舒服,所以把其中一层搞掉换成if

改进的Python代码:

class Solution:
    """
    @param: numbers: An array of Integer
    @param: target: target = numbers[index1] + numbers[index2]
    @return: [index1 + 1, index2 + 1] (index1 < index2)
    """
    def twoSum(self, numbers, target):
        result = []
        i = 0
        j = 1
        while i < len(numbers) and j != i:
            if target == (numbers[i]+numbers[j]):
                result.append(i)
                result.append(j)
                break
            elif j == len(numbers)-1:
                i = i + 1
                j = i + 1
            else:
                j = j+1
        return result

  

加油!!!

以上是关于两数之和(简单)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 两数之和 twoSum

两数之和(简单)

力扣——两数之和

力扣——两数之和

Leetcode简单1. 两数之和JavaScript

力扣1两数之和(简单)