算法
題目:
引用:https://leetcode-cn.com/probl...
具體題目:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
代碼:
public class SumFind {
private int[] find(int[] resource, int target) {
int[] index = new int[2];
for (int i = 0; i < (resource.length - 2); i++) {
if (resource[i] <= target) {
for (int j = i + 1; j < resource.length - 1; j++) {
if (target == (resource[i] + resource[j])) {
index[0] = i;
index[1] = j;
}
}
}
}
return index;
}
}
最好時間複雜度:
數組裏面的元素都大於目標數,所以不會去循環裏面的代碼,所以複雜度就是外面的循環就是N-1,也就是O(n)
最壞時間複雜度:
把裏面的每一個循環完之後才找到這兩個數。所以每一次循環就是n + (n-1) + (n-2) + ... + 1
(1 + n) /2,也是O(n).