2019年4月28日

目录

​题目​​​​两数之和​

​解决​

​1)第一种方法:循环嵌套​

​2)第二种方法:(性能完善)​

​3)其他高级优化:(算法优化)​


题目:两数之和

LeetCode刷题之旅(简单-1):两数之和_算法优化

class Solution {
public int[] twoSum(int[] nums, int target) {

}
}

解决

1)第一种方法:循环嵌套

package leetCode;

import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;

public class twoSum {
public static int[] twoSum(int[] nums, int target){
for (int index = 0; index <= (nums.length -2) ; index++){
int firstNum = nums[index];
for (int index2 = index + 1;index2 <= nums.length -1; index2++){
int secondNum = nums[index2];
if (firstNum + secondNum == target){
ArrayList<Integer> result = new ArrayList<>();
result.add(index);
result.add(index2);
int[] d = new int[result.size()];
for(int i = 0;i<result.size();i++) {
d[i] = result.get(i);
}
return d;
}
}
}
return null;
}

public static void main(String[] args){
int test[] = {3,2,4};
int target = 6;
int[] result = twoSum(test, target);
System.out.println(JSONObject.toJSON(result));
}
}

性能消耗:

LeetCode刷题之旅(简单-1):两数之和_json_02

分析:

1.局部变量使用:firstNum、secondNum、result、d;无疑使用太多了;

 

2)第二种方法:(性能完善)

class Solution {
public int[] twoSum(int[] nums, int target) {
for (int index = 0; index <= (nums.length -2) ; index++){
for (int index2 = index + 1;index2 <= nums.length -1; index2++){
if (nums[index] + nums[index2] == target){
int d[] = new int[2];
d[0]=index;
d[1]=index2;
return d;
}
}
}
return null;
}
}

性能消耗:

LeetCode刷题之旅(简单-1):两数之和_json_03

 

3)其他高级优化:(算法优化)

待补充。