码迷,mamicode.com
首页 > 其他好文 > 详细

两数之和(简单)

时间:2017-12-28 21:31:20      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:第一个   for循环   target   等于   java   param   code   length   write   

给一个整数数组,找到两个数使得他们的和等于一个给定的数 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

  

加油!!!

两数之和(简单)

标签:第一个   for循环   target   等于   java   param   code   length   write   

原文地址:https://www.cnblogs.com/KanHin/p/8137441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!