LeetCode: Array 01[C++, Python]

Lucid·2023년 3월 16일
0

[Python] Given a binary array nums, return the maximum number of consecutive 1's in the array.

class Solution:
    def __init__(self):
        self.result = 0
    def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
        temp = 0;
        temp_standard = 0;
        temp_recent = 0;
        for i in nums:
            if i == 1:
                temp += 1 
            else:
                temp_recent = temp
                if temp_standard < temp_recent:
                    temp_standard = temp_recent                
                temp = 0
        temp_recent = temp
        if temp_standard < temp_recent:
            temp_standard = temp_recent
        return temp_standard
  • 클래스의 작성
  • Python에서는 ++대신 temp += 1

[C++] Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int temp = 0;
        for(auto iter = nums.begin(); iter < nums.end(); iter++) {
            int num = *(iter);
            *(iter) = num*num;
        }
        while(1) {
            int flag = 0;
            for(auto iter = nums.begin(); iter < nums.end() - 1; iter++) {
                if(*iter > *(iter+1)) {
                    temp = *(iter+1);
                    *(iter+1) = *(iter);
                    *(iter) = temp;
                    flag++;
                }
            }
            if(flag == 0)
                break;
        }
        return nums;
    }
};
  • STL 반복자의 사용
    - end() 함수는 컨테이너의 마지막 요소 + 1을 가리킴
    - iter는 포인터

[Python] Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note: that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

class Solution:
    def duplicateZeros(self, arr: list[int]) -> None:
        i = 0
        while i < len(arr):
            if arr[i] == 0:
                arr.insert(i+1, 0)
                del arr[-1]
                i += 2
            else:
                i += 1
profile
JY Park의 블로그

0개의 댓글