題號:2007 標題:Find Original Array From Doubled Array 難度Medium
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
Example 2:
Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.
Constraints:
• 1 <= changed.length <= 105
• 0 <= changed[i] <= 105
我的程式碼
class Solution {
public int[] findOriginalArray(int[] changed) {
int[] result = new int[(changed.length)/2];
List<Integer> result2 = new ArrayList<>();
int i,j=0,k=0,count0=0,count;
//k = (changed.length)/2-1;
if((changed.length)%2!=0){
// System.out.println(changed.length);
return new int[0];
}
Arrays.sort(changed);
int temp;
// for(i=0;i<(changed.length);i++){
// System.out.print(changed[i]+ "," );
// }
j=0;
for(i=0;i<changed.length-1;i++){
if(changed[i]==0){
if(changed[i]==changed[i+1]){
result[j]=changed[i];
j++;
i++;
count0++;
}
count0++;
}else{
break;
}
}
if(count0%2!=0){
return new int[0];
}
if(count0==0){
i=0;
}else{
i=count0;
}
for(;i<changed.length-1;i++){
if(changed[i] != -1){
int chk = 0;
for(k=i+1;k<changed.length;k++){
if(changed[i]*2==changed[k]){
System.out.print(changed[i]+ ","+ changed[k]);
result[j]=changed[i];
j++;
changed[k] = -1;
chk =1;
break;
}
}
if(chk==0){
return new int[0];
}}
}
return result;
}
}
DAY15心得
這幾天就先這樣吧,沒什麼特別的