雙層循環遍歷方法時LeetCode給出的標準答案如下:public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] == target - nums[i]) { return new int[] { i, j };
}
}
} throw new IllegalArgumentException("No two sum solution");
}我覺得最外層的 nums.length 需要改為 nums.length-1才對吧,如果數組有4個元素,那么全程比較 3 趟就可以了,和冒泡排序的外層循環一個道理還是說標準答案這個寫有什么隱含用意呢?望賜教
- 1 回答
- 0 關注
- 3160 瀏覽
添加回答
舉報
0/150
提交
取消