leetcode2-Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

python2.7:

# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 14:58:19 2018

@author: Administrator
"""
#算法解决的问题:从数组x中找到两个数,使其和为target
x=input('input please:')
target=input('input again:')
b=[]
for i in range(len(x)):
    a=target-x[i]
    for j in range(len(x))[i+1:]:
        if a==x[j]:
            b.append([i,j])
print '结果是:%s'%b


我的java写的:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n=nums.length;
        int[] p=new int[2];
        int ron,i;
        for(int j=0;j<n-1;j++){
            ron=target-nums[j];
           i=j+1;
            for(;i<n;i++){
                if(ron==nums[i]){
                    p[0]=j;
                    p[1]=i;
                    return p;
                }
            }
        }
        return p;
    }
}

官方答案:

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");
}

猜你喜欢

转载自blog.csdn.net/u011776818/article/details/80869441