原题地址: https://leetcode.com/problems/two-sum/description/
题目大意: 给定一个数组以及目标数字,计算数组中哪两个数字只和为目标数字并返回这两个数字在数组中的位置索引。
解析: 通过遍历数组中每一个数字,进行两层循环,判断这两个数字之和是否为目标数字,随后返回符合条件的数字索引。
具体代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int [] sumArray = new int[2];
int l = nums.length;
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if(i == j){
continue;
}else{
int sum = nums[i] + nums[j];
if(sum == target){
sumArray[0] = i;
sumArray[1] = j;
return sumArray;
}
}
}
}
return sumArray;
}
}
不足: 答主的解题算法较为简单粗暴,相对算法复杂度为O(N2)。算法仍需优化。