iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
AI & Data

想到甚麼打甚麼系列 第 15

找LeetCode上簡單的題目來撐過30天啦(DAY15)

  • 分享至 

  • xImage
  •  

題號: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]:

  • Twice the value of 1 is 1 * 2 = 2.
  • Twice the value of 3 is 3 * 2 = 6.
  • Twice the value of 4 is 4 * 2 = 8.
    Other original arrays could be [4,3,1] or [3,1,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心得
這幾天就先這樣吧,沒什麼特別的


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY14)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY16)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言