算法算法
題目:
引用:https://leetcode-cn.com/probl...
具體題目:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。數組
給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
代碼:code
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)leetcode
最壞時間複雜度:
把裏面的每個循環完以後才找到這兩個數。因此每一次循環就是n + (n-1) + (n-2) + ... + 1
(1 + n) /2,也是O(n).get