1. Two Sum - LeetCode
2017-08-17 本文已影响0人
037e3257fa3b
LeetCode Problems Solutions
question description: 问题描述
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].
Thinking
基本排序算法中的选择排序是假定第0个为最小的,然后通过两次循环逐次比较(面试常见的基本排序算法)。我们也可以借助该思想,假定两个数中的第一个数是从第一个开始的,通过两次循环来获得两个数的索引。
solution with java - Java解决方案
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++){
int first = nums[i];
for ( int j = i + 1; j < nums.length ; j++){
int secode = nums[j];
if ( first + secode == target){
return new int[]{i,j};
}
}
}
return new int[]{0,0};
}
solution with swift - swift解决方案
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0 ..< nums.count {
let first = nums[i];
for j in (i+1) ..< nums.count {
let seconde = nums[j];
if first + seconde == target {
return [i,j];
}
}
}
return [0,0];
}