LeetCode Week 3

LeetCode Week 3

卧推 硬拉 深蹲

问题集合

1.Two Sum II - Input array is sorted(Easy 167)

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
    int x = 0, y = numbersSize - 1;

    while (x < y) {
        if (numbers[x] + numbers[y] == target) break;
        if (numbers[x] + numbers[y] < target) x++;
        else y--;
    }

    int *result = (int *)malloc(sizeof(int) * 2);
    *returnSize = 2;
    result[0] = x + 1;
    result[1] = y + 1;
    return result;
}

2.Move Zeroes (Easy 283)

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.
Solution:

void moveZeroes(int* nums, int numsSize) {
    int i = 0, j = 0;

    while (j < numsSize) {
        while (j < numsSize && nums[j] == 0) j++;
        if (j < numsSize) {
            nums[i++] = nums[j++];
        }
    }

    for (int k = i; k < numsSize; k++) {
        nums[k] = 0;
    }
}

3.Add Digits (Easy 258)

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Solution:

int addDigits(int num) {
    if (0 == num) return 0;
    if (0 == num % 9) return 9;

    return num % 9;
}

4.Single Number III (Medium 260)

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:

1.The order of the result is not important. So in the above example, [5, 3] is also correct.
2.Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* singleNumber(int* nums, int numsSize, int* returnSize) {
    int x = 0, y = 0;
    int tmp = 0;
    int mask = 1;

    for (int i = 0; i < numsSize; i++) {
        tmp ^= nums[i];
    }

    // 位操作符优先级好低...
    while ((tmp & 1) == 0) {
        mask <<= 1;
        tmp >>= 1;
    }

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] & mask) {
            x ^= nums[i];
        }
        else {
            y ^= nums[i];
        }
    }

    int* result = (int *)malloc(sizeof(int) * 2);
    *returnSize = 2;
    result[0] = x;
    result[1] = y;
    return result;
}

5.Product of Array Except Self (Medium 238)

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
    int *result = (int *) malloc(sizeof(int) * numsSize);
    for (int i = 0; i < numsSize; i++) {
        result[i] = 1;
    }
    *returnSize = numsSize;
    int start2End = 1, end2Start = 1;

    for (int i = 0; i < numsSize; i++) {
        result[i] *= start2End;
        start2End *= nums[i];
        result[numsSize - i - 1] *= end2Start;
        end2Start *= nums[numsSize - i - 1];
    }

    return result;
}

6.Friend Circles (Medium 547)

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:

Input: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. 
The 2nd student himself is in a friend circle. So return 2.

Example 2:

Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, 
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Note:
1.N is in range [1,200].
2.M[i][i] = 1 for all students.
3.If M[i][j] = 1, then M[j][i] = 1.
Solution:

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        int *leader, *flag;
        leader = (int *)malloc(sizeof(int) * M.size());
        flag = (int *)malloc(sizeof(int) * M.size());
        init(leader, M.size());
        init(flag, M.size());

        queue<int> visit;
        for (int i = 0; i < M.size(); i++) {
            if (leader[i] != -1) continue;
            init(flag, M.size());
            visit.push(i);
            flag[i] = 1;

            while(!visit.empty()) {
                int num = visit.front();
                visit.pop();

                for (int j = 0; j < M.size(); j++) {
                    if (M[num][j] == 1 && flag[j] == -1) {
                        visit.push(j);
                        flag[j] = 1;
                    }
                }
            }

            for (int j = 0; j < M.size(); j++) {
                if (flag[j] == 1) {
                    leader[j] = i;
                }
            }
        }

        init(flag, M.size());
        int count = 0;

        for (int i = 0; i < M.size(); i++) {
            if (flag[leader[i]] == -1) {
                count ++;
                flag[leader[i]] = 1;
            }
        }

        return count;
    }
private:
    void init(int *arr, int size) {
        for (int i = 0; i < size; i++) {
            arr[i] = -1;
        }
    }
};

7.Diagonal Traverse (Medium 498)

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output:  [1,2,4,7,5,3,6,8,9]
Explanation:

Note:
1.The total number of elements of the given matrix will not exceed 10,000.

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findDiagonalOrder(int** matrix, int matrixRowSize, int matrixColSize, int* returnSize) {
    int *result = (int *)malloc(sizeof(int) * matrixRowSize * matrixColSize);
    *returnSize = matrixRowSize * matrixColSize;
    int direct = 1;
    int index = 0;
    int x = 0, y = 0;

    for (int i = 0; i < matrixRowSize + matrixColSize; i++) {
        while (x >= 0 && x < matrixRowSize && y >= 0 && y < matrixColSize) {
            result[index++] = matrix[x][y];
            x -= direct;
            y += direct;
        }

        x += direct;
        y -= direct;

        if (direct == 1) {
            if (y < matrixColSize - 1) {
                y++;
            }
            else {
                x++;
            }
        }
        else {
            if (x < matrixRowSize - 1) {
                x++;
            }
            else {
                y++;
            }
        }

        direct *= -1;
    }
    return result;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值