2022年3月15日 星期二

LeetCode 1. Two Sum

 https://leetcode.com/problems/two-sum/


題目是Input是一個陣列,且沒有排序,需要將兩數相加,回傳該兩數的位置,且兩個位置不能相同。
範例:
Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

解題:

class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] b = new int[2];
for(int i=0; i<numbers.length; i++){
for(int j=numbers.length-1; j>i; j--){
if (numbers[i] + numbers[j] == target){
b[0] = i;
b[1] = j;
return b;
}
}
}
return b;
}
}

Success

Runtime: 85 ms, faster than 23.06%of Java online submissions for Two Sum.

Memory Usage: 45.2 MB, less than 31.21%of Java online submissions for Two Sum.

感覺這速度跑得有點慢
該開始優化看看


一樣是在前後先判斷在判斷兩個相加
速度就變快很多

class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] b = new int[2];
for(int i=0; i<numbers.length; i++){
if(i > 0 && numbers[i] + numbers[i-1] == target){
b[0] = i;
b[1] = i-1;
return b;
}
for(int j=numbers.length-1; j>i; j--){
if(j < numbers.length-1 && numbers[j] + numbers[j+1] == target){
b[0] = j;
b[1] = j+1;
return b;
}
if (numbers[i] + numbers[j] == target){
b[0] = i;
b[1] = j;
return b;
}
}
}
return b;
}
}

Success

Runtime: 0 ms, faster than 100.00%of Java online submissions for Two Sum.

Memory Usage: 42.5 MB, less than 67.21%of Java online submissions for Two Sum.

沒有留言:

張貼留言

Android Studio IDE 錯誤

 :app:compile xxxxx JavaWithJavac FAILED An exception has occurred in the compiler (1.8.0_312). Please file a bug against the Java compiler ...