leetcode Day33----array.easy

这篇博客介绍了两个LeetCode题目,一个是将数组形式的整数加法,另一个是关于国际象棋中车可以捕获的棋子数量。前者涉及到将整数A加上K并保持数组形式,后者关注于在一个8x8棋盘上计算车能够捕获的黑色棋子数目。博客中包含了用JAVA和C语言实现的解题代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Add to Array-Form of Integer

For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].

Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.

Example 1:

Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
Example 2:

Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455
Example 3:

Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021
Example 4:

Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Note:

1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
If A.length > 1, then A[0] != 0

JAVA

class Solution {
    public List<Integer> addToArrayForm(int[] A, int K) {
        LinkedList<Integer> res = new LinkedList<>();
        int carry = 0;
        int index = A.length - 1;
        while(K > 0 || index >= 0){
            int curK = K % 10;
            int curA = index >= 0 ? A[index]: 0;
            int curDigitSum = curK + curA + carry;
            int toBeAdded = curDigitSum % 10;
            carry = curDigitSum / 10;
            index --;
            K /= 10;
            res.addFirst(toBeAdded);
        }
        if(carry != 0){
            res.addFirst(1);
        }
        return res;
    }
}

Success
Details
Runtime: 4 ms, faster than 98.10% of Java online submissions for Add to Array-Form of Integer.
Memory Usage: 39.3 MB, less than 97.85% of Java online submissions for Add to Array-Form of Integer.

class Solution {
    public List<Integer> addToArrayForm(int[] A, int K) {
        List<Integer> list = new LinkedList<>();
        
        int i = A.length - 1;
        int carry = 0;
        while(i >= 0 || K != 0 || carry == 1){
            int sum = carry;
            if(i >= 0){
                sum += A[i];
                i--;
            }
            if(K != 0){
                sum += K % 10;
                K = K / 10;
            }
            list.add(0,sum % 10);
            carry = sum / 10;   
        }
        return list;
    }
}

Success
Details
Runtime: 5 ms, faster than 95.99% of Java online submissions for Add to Array-Form of Integer.
Memory Usage: 38.7 MB, less than 98.76% of Java online submissions for Add to Array-Form of Integer.

C

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* addToArrayForm(int* A, int ASize, int K, int* returnSize){
    int *result=(int *)malloc(sizeof(int)*10001);
    int k=10000;
    int i=ASize-1;
    int carry=0, sum=0;
     while(K && i>=0){ 
         sum= (A[i]+(K%10)+carry);
         result[k--]=sum%10;
         carry=sum/10;
         K=K/10;
         i--;
     }
    if(K){
        while(K){
            sum=K%10+carry;
            result[k--]=sum%10;
            carry=sum/10;
            K=K/10;
        }
    }
    if(i>=0){
        while(i>=0){
            sum=A[i]+carry;
            result[k--]=sum%10;
            carry=sum/10;
            i--;
        }
    }
    if(carry>0){
        result[k--]=carry;
    }
    *returnSize=10000-k;
    return &result[k+1];
}


Success
Details
Runtime: 76 ms, faster than 100.00% of C online submissions for Add to Array-Form of Integer.
Memory Usage: 19.7 MB, less than 11.67% of C online submissions for Add to Array-Form of Integer.

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* addToArrayForm(int* A, int ASize, int K, int* returnSize){
    if(ASize <= 0 || !A)
        return NULL;
    int str_len = snprintf( NULL, 0, "%d", K ) + 1;
    char str[str_len];
    snprintf(str, str_len, "%d", K);
    int num_size = str_len - 1;
    int num[num_size];
    int ret_size = (num_size > ASize)?num_size:ASize;
    int *ret = calloc(ret_size, sizeof(int));
    for(int i = 0; i < num_size; ++i)
        num[i] = str[i] - '0';

    int temp_sum = 0;
    int carry = 0;
    for(int i = ASize - 1, j = num_size - 1, ret_ctr = ret_size - 1; ret_ctr >= 0; --i, --j, --ret_ctr){
        temp_sum = 0;
        if(i >= 0)
            temp_sum += A[i];
        if(j >= 0)
            temp_sum += num[j];
        temp_sum += carry;
        if(temp_sum >= 10) {
            ret[ret_ctr] = temp_sum % 10;
            carry = temp_sum / 10;
            if(ret_ctr == 0) {
                int* new_ret = realloc(ret, (ret_size + 1) * sizeof(int));
                ret_size += 1;
                ret = new_ret;
                memmove(&ret[1], &ret[0], (ret_size-1)*sizeof(*ret));
                ret[0] = carry;
            }
        } else {
            ret[ret_ctr] = temp_sum;
            carry = 0;
        }
    }
    
    *returnSize = ret_size;
    return ret;
}


Success
Details
Runtime: 76 ms, faster than 100.00% of C online submissions for Add to Array-Form of Integer.
Memory Usage: 19.7 MB, less than 11.67% of C online submissions for Add to Array-Form of Integer.

Available Captures for Rook

On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters ‘R’, ‘.’, ‘B’, and ‘p’ respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.

The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.

Return the number of pawns the rook can capture in one move.

Example 1:
在这里插入图片描述

Input: [[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",“R”,".",".",".",“p”],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.

Example 2:
在这里插入图片描述

Input: [[".",".",".",".",".",".",".","."],[".",“p”,“p”,“p”,“p”,“p”,".","."],[".",“p”,“p”,“B”,“p”,“p”,".","."],[".",“p”,“B”,“R”,“B”,“p”,".","."],[".",“p”,“p”,“B”,“p”,“p”,".","."],[".",“p”,“p”,“p”,“p”,“p”,".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation:
Bishops are blocking the rook to capture any pawn.

Example 3:
在这里插入图片描述
Input: [[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",“p”,".",".",".","."],[“p”,“p”,".",“R”,".",“p”,“B”,"."],[".",".",".",".",".",".",".","."],[".",".",".",“B”,".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
The rook can capture the pawns at positions b5, d6 and f5.

Note:

board.length == board[i].length == 8
board[i][j] is either ‘R’, ‘.’, ‘B’, or ‘p’
There is exactly one cell with board[i][j] == ‘R’

JAVA

class Solution {
    public int numRookCaptures(char[][] board) {
        int[] point = new int[2];
        for(int i = 0 ; i < 8 ; i++) {
            for(int j = 0 ; j < 8 ; j++) {
                if(board[i][j] == 'R') {
                    point[0] = i;
                    point[1] = j;
                    break;
                }
            }
        }
        int count = 0;
        int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
        for(int[] dir : dirs) {
            int x = point[0] + dir[0];
            int y = point[1] + dir[1];
            while(x >= 0 && y >= 0 && x < 8 && y < 8 && board[x][y] == '.') {
                x += dir[0];
                y += dir[1];
            }
            if(x < 0 || y < 0 || x >= 8 || y >= 8) continue;
            if(board[x][y] == 'p') count++;
        }
        return count;
    }
}

Success
Details
Runtime: 0 ms, faster than 100.00% of Java online submissions for Available Captures for Rook.
Memory Usage: 33 MB, less than 99.97% of Java online submissions for Available Captures for Rook.

class Solution {
    public int numRookCaptures(char[][] board) {
        for (int i=0;i<8;i++){
            for (int j=0;j<8;j++){
                if( board[i][j] == 'R' ){
                    return getKill(i,j,"white",board);
                }
                else if(board[i][j]=='r'){
                    return getKill(i,j,"black",board);
                }
            }
        }
        return -1;
    }
    
    public int getKill(int row, int col, String color,char[][] brd){
        char oppB ='B';
        char oppP = 'P';
        int count = 0;
        if(color.equals("white")){
            oppB = 'b';
            oppP = 'p';
            System.out.println("WHITE");
        }
        for (int i = row+1; i<8;i++){
            System.out.println("row incre ");
            if (brd[i][col]==oppB || brd[i][col]==oppP){
                count++;
                break;
            }
            else if (brd[i][col]!='.'){
                break;
            }
        }
        for (int i = row-1; i>=0;i--){
            System.out.println("row dec ");
            if (brd[i][col]==oppB || brd[i][col]==oppP){
                count++;
                break;
            }
            else if (brd[i][col]!='.'){
                break;
            }
        }
        
        for (int i = col-1; i>=0;i--){
            System.out.println("col dec ");
            if (brd[row][i]==oppB || brd[row][i]==oppP){
                count++;
                break;
            }
            else if (brd[row][i]!='.'){
                break;
            }
        }
        
        for (int i = col+1; i<8;i++){
            System.out.println("col incre ");
            if (brd[row][i]==oppB || brd[row][i]==oppP){
                count++;
                break;
            }
            else if (brd[row][i]!='.'){
                break;
            }
        }
        
        return count;
    }
}

Success
Details
Runtime: 2 ms, faster than 61.67% of Java online submissions for Available Captures for Rook.
Memory Usage: 33.3 MB, less than 99.97% of Java online submissions for Available Captures for Rook.

C

int numRookCaptures(char** board, int boardSize, int* boardColSize){
    int count = 0;
    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < sizeof(boardColSize); j++) {
            if (board[i][j] == 'R') {
                if (i+1 < 8) {
                    for (int k = i+1; k < 8; k++) {
                        if (board[k][j] == 'p') {
                            count++;
                            break;
                        } 
                        else if (board[k][j] == '.') {
                            continue;
                        } 
                        else {
                            break;
                        }
                    }
                }
                if (i-1 >= 0) {
                    for (int k = i-1; k >= 0; k--) {
                        if (board[k][j] == 'p') {
                            count++;
                            break;
                        } 
                        else if (board[k][j] == '.') {
                            continue;
                        } 
                        else {
                            break;
                        }
                    }  
                }
                
                if (j+1 < 8) {
                    for (int k = j+1; k < 8; k++) {
                        if (board[i][k] == 'p') {
                            count++;
                            break;
                        } 
                        else if (board[i][k] == '.') {
                            continue;
                        } 
                        else {
                            break;
                        }
                    }
                }

                if (j-1 >= 0) {
                    for (int k = j-1; k >= 0; k--) {
                        if (board[i][k] == 'p') {
                            count++;
                            break;
                        } 
                        else if (board[i][k] == '.') {
                            continue;
                        } 
                        else {
                            break;
                        }
                    }
                }
            }
        }
    }
    return count;
}

Success
Details
Runtime: 0 ms, faster than 100.00% of C online submissions for Available Captures for Rook.
Memory Usage: 6.9 MB, less than 5.00% of C online submissions for Available Captures for Rook.

Find Common Characters

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

You may return the answer in any order.

Example 1:

Input: [“bella”,“label”,“roller”]
Output: [“e”,“l”,“l”]
Example 2:

Input: [“cool”,“lock”,“cook”]
Output: [“c”,“o”]

Note:

1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter

JAVA

class Solution {
    public List<String> commonChars(String[] A) {
       int[] count = new int[26];
        Arrays.fill(count, Integer.MAX_VALUE);

        for (int i = 0; i < A.length; i++) {
            int[] curCount = new int[26];
            for (char c : A[i].toCharArray()) {
                curCount[c - 'a']++;
            }

            for (int j = 0; j < 26; j++) {
                count[j] = Math.min(count[j], curCount[j]);
            }
        }

        List<String> ans = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < count[i]; j++) {
                ans.add("" + (char)('a' + i));
            }
        }
        return ans; 
    }
}

Success
Details
Runtime: 5 ms, faster than 84.21% of Java online submissions for Find Common Characters.
Memory Usage: 36.1 MB, less than 99.87% of Java online submissions for Find Common Characters.

C

#define totalLetters 26

int search(char letter, int currentCnt,  char ** A, int ASize){
    int count = 0;
    int min = currentCnt;
    
    for (int i = 1; i < ASize; i++){
        count = 0;
        for (int j = 0; A[i][j] != '\0'; j++){
            if (letter == A[i][j]){
                count++;
            }
        }
        
        if (count <= 0){
            return 0;
        }
        min = (min <= count) ? min : count;       
    }
    return min;
}


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char ** commonChars(char ** A, int ASize, int* returnSize){
    int str1Hash[totalLetters];
    memset(str1Hash, 0, sizeof(str1Hash));
    
    int str1Size = 0;
    
    for (int i = 0; A[0][i] != '\0'; i++){
        int index = A[0][i] - 'a';
        str1Hash[index]++;
        str1Size++;
    }
    
    char ** resultList = (char **)malloc(str1Size * sizeof(char *));
    
    for (int i = 0; i < str1Size; i++){
        resultList[i] = malloc(2 * sizeof(char));
    }

    int resultListPtr   = 0;
    int resultListSize  = 0;
    int result;
    
    for (int i = 0; i < totalLetters; i++){
        if (str1Hash[i] > 0){
            result = search('a' + i, str1Hash[i], A, ASize);
            for (int j = 0; j < result; j++){
                memset(resultList[resultListPtr], '\0', 2);
                resultList[resultListPtr++][0] = 'a' + i;
                resultListSize++;        
            }
        }
    }
    
    *returnSize = resultListSize;
    return resultList;
}

Success
Details
Runtime: 4 ms, faster than 98.05% of C online submissions for Find Common Characters.
Memory Usage: 7.6 MB, less than 70.85% of C online submissions for Find Common Characters.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值