https://leetcode.com/problems/two-sum/
讓陣列中每個元素 逐一和右邊每個數相加,若結果等於target,將值放入ans陣列裡
class Solution {
public int[] twoSum(int[] nums, int target) {
int []ans =new int[2];
boolean stop = false;
for(int i = 0; i<nums.length-1; i++){ //檢查陣列長度-1次就好
for(int n = 1; n<nums.length-i; n++){ //因為不需要跟自己做相加,因此n從1開始,當前index加上長度-1,逐一做判斷
if(nums[i] + nums[i+n]==target){
ans[0] = i;
ans[1] = i+n;
stop =true;
break;
}
}
if(stop) break;
}
return ans;
}
}
最後附上leecode紀錄跑最快的code
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 1; i < nums.length; i++) {
for (int j = i; j < nums.length; j++) {
if (target == nums[j] + nums[j-i]) {
return new int[]{j-i, j};
}
}
}
return new int[2];
}
}
留言列表