3Sum
我覺得做算法題,一般在不能一下子給出最終的解得時候,應該循序漸進的結局問題,先給出一個近似正確的答案,並進行不斷地修正,一步一步的逼近最終得答案,就向這道題一樣,可以先實現有重複解得程序,再在這個程序的基礎上實現無重複的解。
package leetcode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class leet15 {
//算法實現將:因爲需要三個數相加,所以需先固定前兩個數,對第三個數進行循環,然後分別對前兩個數的下標進行加1操作,如果
//如果執行加一操作以後的第一個數和前一輪循環的第一個數相等,則此次循環結束,即就是如果有兩個相鄰的數相等就減少一次循環。
public static List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> result = new ArrayList<List<Integer>>();//存儲最終的返回結果
for(int i = 0;i < nums.length - 2;i++){//固定前兩個數
List<Integer> inter =new ArrayList<Integer>();//保存每一個相加爲0的三個數,即就是最終結果的內部元素
for(int j = 0;j < nums.length;j++){//循環第三個數
if(i > 0){//第一次循環時i=0所以沒有i-1,只能是在i>0的時候才能判斷
if(nums[i] == nums[i-1])//如果執行加一操作以後的第一個數和前一輪循環的第一個數相等,則此次循環結束,
//即就是如果有兩個相鄰的數相等就減少一次循環
continue;
}
if(j == i-1||j == i||j==i+1)//相加的三個數下標不能相同
continue;
if(nums[i] + nums[i+1] + nums[j] == 0)
{
inter.add(nums[i]);
inter.add(nums[i+1]);
inter.add(nums[j]);
result.add(inter);
}
}
}
return result;
}
public static int[] bubbleSort(int[] array){//冒泡排序將原數組進行從小到大的排序
for(int i = 0;i < array.length;i++){
for(int j = 1;j < array.length - i;j++){
if(array[j] < array[j-1]){
int temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
return array;
}
public static void main(String[] args) {//主函數
int[] array = {-1,0,1,2,-1,-4};
array = bubbleSort(array);
List<List<Integer>> list = leet15.threeSum(array);
Iterator<List<Integer>> iter = list.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
}
}