題號:15 標題:3Sum 難度:Medium
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int[] temp = new int[3];
List<Integer> result2 = new ArrayList<Integer>();
int i,j,z;
for(i=0;i<nums.length-2;i++){
for(j=i+1;j<nums.length-1;j++){
for(z=j+1;z<nums.length;z++){
if (nums[i] +nums[j]+nums[z]==0 ){
System.out.println(nums[i]+ ","+nums[j]+","+nums[z]);
temp[0] = nums[i];
temp[1] = nums[j];
temp[2] = nums[z];
Arrays.sort(temp);
result2 = Arrays.asList(temp[0],temp[1],temp[2]);
if(!result.contains(result2)){
result.add(result2);
}
}
}
}
}
return result;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int[] temp = new int[3];
List<Integer> result2 = new ArrayList<Integer>();
int i,j,z;
Arrays.sort(nums);
if(nums.length < 3){
return result;
}
for(i=0;i<nums.length-2;i++){
if(i!=0 && nums[i]== nums[i-1]){
//i++;
continue;
}
j=i+1; z = ((nums.length)-1);
//System.out.println("1:"+i+","+j+","+z);
int target;
while(true){
target = nums[i]+nums[j]+nums[z];
if(j >= z){
break;
}
if(target>0){
z--;
}else if(target<0){
j++;
}else if(target==0){
result.add(Arrays.asList(nums[i],nums[j],nums[z]));
//System.out.println("2:"+i+","+j+","+z);
z--;
j++;
while(nums[z]== nums[z+1]){
if(j >= z){
break;
}
z--;
}
while(nums[j]== nums[j-1]){
if(j >= z){
break;
}
j++;
}
}
}
}
return result;
}
}
花比較久的時間
用三層for會超時,感謝團長台積電辣妹提示此題解
是說知道解法後原本想把nums陣列存成arraylist做判斷,結果就爆炸ㄌ,邏輯沒換,用原本得nums陣列直接下去判讀,一切正常,就當我改錯了甚麼吧,懶的抓bug了
DAY12心得
明日的我得去看醫生,後天的後天得去考照,我覺得我完蛋了,沒一項目有100%把握的,嗚嗚嗚