본문 바로가기

Algorithm/Leet Code

LeetCode #888 FairCandySwap. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,그래프,Graph,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접

LeetCode #888 FairCandySwap. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,그래프,Graph,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접

 

 

Runtime: 1244 ms, faster than 5.02% of C++ online submissions for Fair Candy Swap.

 

Memory Usage: 12.3 MB, less than 80.00% of C++ online submissions for Fair Candy Swap.

 

 

최대개수 사탕 동적테이블 만들면 퍼포먼스/메모리 뒤집을 수 있을 듯함

 

I think it could be changed performance / memory if I use dynamic table of candies

 

LeetCode #888

Q.

 Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.

Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy.  (The total amount of candy a person has is the sum of the sizes of candy bars they have.)

Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange.

If there are multiple answers, you may return any one of them.  It is guaranteed an answer exists.

 

 앨리스와 밥은 각자 다른 개수의 캔디바들을 갖고 있다. A[i] 는 앨리스가 가지고 있는 캔디바의 i 번째 개수이고, B[j] 는 밥이 가지고 있는 캔디바의 j 번째 캔디바 개수이다.

 그들은 친구이기 때문에, 캔디바 한개를 교환해서 둘이 갖고 있는 전체 캔디 개수를 맞추고 싶어한다.

 정수배열 ans 를 반환하는데, ans[0] 은 앨리스가 바꿔야하는 캔디바의 사이즈이고, ans[1] 은 밥이 바꿔야하는 캔디바의 사이즈이다.

 답이 여러개면, 그중 아무거나 1개만 리턴해라. 답은 무조건 있다고 보장한다.

 

 

Example 1:

 

Input: A = [1,1], B = [2,2]

Output: [1,2]

 

 

Example 2:

 

Input: A = [1,2], B = [2,3]

Output: [1,2]

 

 

Example 3:

 

Input: A = [2], B = [1,3]

Output: [2,3]

 

 

Example 4:

 

Input: A = [1,2,5], B = [2,4]

Output: [5,4]

 

 

 

Note:

  • 1 <= A.length <= 10000
  • 1 <= B.length <= 10000
  • 1 <= A[i] <= 100000
  • 1 <= B[i] <= 100000
  • It is guaranteed that Alice and Bob have different total amounts of candy.
  • It is guaranteed there exists an answer.

 

 

Process

// Process
//1. Input Alice's candies and Bob's candies
//2. Get total candy each and get fair amount of candy
//3. Find changingNumber
//4. Return change number

 

 

// 처리과정

//1. 앨리스와 밥의 캔디바 배열을 입력받는다.

//2. 각자의 전체 개수와 바뀌어야 하는 캔디수를 구해둔다.

//3. 각자의 바뀌게 되는 캔디바를 구한다.

//4. 결과 반환한다.

 

 

Code.. lemme see example code!!!

코드.. 예제코드를 보자!!!

 

 

 

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        vector<int> resultVector;
        
        // 2.
        int sumA = 0;
        for (int i = 0; i < A.size(); ++i) {
            sumA += A[i];
        }
        int sumB = 0;
        for (int i = 0; i < B.size(); ++i) {
            sumB += B[i];
        }
        
        // 3.
        int fairDiff = abs(sumA - (sumA + sumB) / 2);
        
        // 4.
        bool isDone = false;
        if (sumA > sumB) {
            for (int i = 0; !isDone && i < A.size(); ++i) {
                for (int j = 0; !isDone && j < B.size(); ++j) {
                    if (A[i] - B[j] == fairDiff) {
                        resultVector.push_back(A[i]);
                        resultVector.push_back(B[j]);
                        isDone = true;
                    }
                }
            }
        } else {
            for (int i = 0; !isDone && i < B.size(); ++i) {
                for (int j = 0; !isDone && j < A.size(); ++j) {
                    if (B[i] - A[j] == fairDiff) {
                        resultVector.push_back(A[j]);
                        resultVector.push_back(B[i]);
                        isDone = true;
                    }
                }
            }
        }
        return resultVector;
    }
};

 

 

 

Something else you might like...?

 

2019/08/14 - [Life/Item review] - Mi Band 4 review, 미밴드4 후기, 장점, 단점, 리뷰, 한글, global review, 미밴드4 글로벌 후기, 리뷰, 구매, 사용방법, setting, 세팅, ProsNCons

 

2019/08/27 - [Programming] - 개발자 선배들에게서 배운 것들. Things I Learnt from a Senior Software Engineer. 코딩 잘하는 방법, how to code well, 소프트웨어,프로그래머,programmer

 

2019/09/17 - [Algorithm/Leet Code] - LeetCode #841 KeysAndRooms. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,그래프,Graph,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접

2019/08/28 - [Algorithm/Leet Code] - LeetCode #821 ShortestDistanceToACharacter. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접..

2019/08/25 - [Algorithm/Leet Code] - LeetCode #191 NumberOf1Bits. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

2019/08/19 - [Algorithm/Leet Code] - LeetCode #942 DI StringMatch. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

2019/07/21 - [Algorithm/Leet Code] - LeetCode #590 N-aryTreePostorderTraversal. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,..

2019/07/20 - [Algorithm/Leet Code] - LeetCode #589 N-aryTreePreorderTraversal. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,..

2019/07/17 - [Algorithm/Leet Code] - LeetCode #905 SortArrayByParity. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리..

2019/07/13 - [Algorithm/Leet Code] - LeetCode #994 RottingOranges. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

2019/06/25 - [Algorithm/Leet Code] - LeetCode #766 ToeplitzMatrix. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

 

 

2019/04/14 - [Programming/C++] - C++ Math - sqrt (square root, 제곱근, 루트). stl, math.h, 씨쁠쁠, example code, 예제코드

 

 

2018/10/19 - [Programming/Design Pattern ] - Design pattern - Prototype (디자인패턴 - 프로토타입) / Java C++ C#

 

 

2019/01/12 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #60 sudoku. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/12 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #59 spiralNumbers. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/08 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #58 messageFromBinaryCode. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/07 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #57 fileNaming. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

 

 

2018/12/28 - [Programming/Software Architecture] - Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 - (#9, Tell, Don't Ask)

2018/12/26 - [Programming/Software Architecture] - Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 (1)

 

 

2019/01/14 - [Programming/Java] - 자바 메모리 누수 체크/확인/고치는 방법, Memory leak check/fix in Java application, cleanCode/좋은코드/oop/객체지향

 

 

2019/02/19 - [Life/Health care] - Lysine 라이신 usage/side effects/dosage 효과/효능/부작용/성인,소아 용법, 복용법

2019/02/16 - [Life/Health care] - Finasteride 피나스테라이드,탈모약 usage/side effects/dosage 효능/부작용/효과/sexual effect/두타스테라이드/프로페시아/propecia/finpecia/카피약/copy drug/hair loss

2019/02/25 - [Life/Health care] - Folic Acid 엽산 vitaminB9,비타민M usage/side effects/dosage 효과/효능/부작용/성인,소아 용법, 복용법

2019/02/28 - [Life/Health care] - Vitamin K, 비타민 K usage/side effects/dosage 효능/부작용/성인,소아 용법

2019/03/03 - [Life/Health care] - Vitamin B1, Thiamine, 비타민 B1, 티아민 usage/side effects/dosage 효능/부작용/성인,소아 용법