[algorithm]Defanging IP address, Flipping Image, DI String Match, Sort Array By Parity 2, Kids With the Greatest Number of Candies, Richest Customer Wealth (LeetCode)

yeon·2021년 5월 26일
0

Defanging IP address는 쉬워서 패스

Flipping an Image (1108)

뒤집고 숫자 치환

public int[][] flipAndInvertImage(int[][] image) {
    int len = image.length;
    int[][] imageArray = new int[len][len];
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
            // 뒤집고 치환
            imageArray[i][j] = 1 - image[i][len - j - 1];
        }
    }
    return imageArray;
}

0을 1로 바꾸고, 1을 0으로 바꾸려면 1 - x 를 하면 된다!

imageArray[i][j] = 1 - image[i][len - j - 1];

DI String Match (942)

public static int[] diStringMatch(String s) {
    int[] result = new int[s.length() + 1];

    int[] arr = new int[s.length() + 1];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }

    int iCount = 0;
    int dCount = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == 'I') {
            result[i] = arr[iCount];
            iCount++;
        } else {
            result[i] = arr[arr.length - 1 - dCount];
            dCount++;
        }
    }
    result[s.length()] = arr[iCount];
    return result;
}

result의 마지막 요소를 어떻게 넣어야할지가 가장 고민이 많이 되었다. dong 덕분에 해결

Sort Array By Parity II(922)

홀수 인덱스에 홀수, 짝수 인덱스에 짝수 아무 경우의 수 반환

홀수 짝수 여부가 인덱스와 다르면 다음거랑 자리 바꾸기

public int[] sortArrayByParityII(int[] nums) {

    for (int i = 0; i < nums.length - 1; i++) {
        if (i % 2 == 0 && nums[i] % 2 != 0) {
            int add = 1;
            while(nums[i] % 2 != 0) {
                int temp = nums[i];
                nums[i] = nums[i + add];
                nums[i + add] = temp;
                add++;
            }
        }

        if (i % 2 != 0 && nums[i] % 2 == 0) {
            int add = 1;
            while(nums[i] % 2 == 0) {
                int temp = nums[i];
                nums[i] = nums[i + add];
                nums[i + add] = temp;
                add++;
            }
        }
    }
    return nums;
}

→ Dong 풀이가 더 좋아보인다. 홀수, 짝수를 새로운 리스트에 담아서 사용하는 방식으로 푸셨다. 다시 풀어보자.

Kids With the Greatest Number of Candies(1431)

public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
    // greatest number 구하기
    int max = 0;
    for (int candy : candies) {
        if (candy > max) {
            max = candy;
        }
    }

    List<Boolean> results = new ArrayList<>();
    for (int i = 0; i < candies.length; i++) {
        if (candies[i] + extraCandies >= max) {
            results.add(true);
        } else results.add(false);
    }
    return results;
}

Richest Customer Wealth

public int maximumWealth(int[][] accounts) {
    int max = 0;
    for (int i = 0; i < accounts.length; i++) {
        int sum = 0;
        for (int j = 0; j < accounts[i].length; j++) {
            sum += accounts[i][j];
        }
        if (sum > max) {
            max = sum;
        }
    }
    return max;
}

0개의 댓글