LeetCode Week 4

2023-11-17

LeetCode Week 4

练腿是最虐的项目,没有之一

问题集合

1.Reverse Words in a String III(Easy 557)

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note:
In the string, each word is separated by single space and there will not be any extra space in the string.

Solution:

char* reverseWords(char* s) {
    int start = 0;
    int length = strlen(s);
    bool findStart = true;

    int i = 0;
    while (i < length) {
        if (findStart) {
            if (s[i] != ' ') {
                start = i;
                findStart = false;
            }
            else {
                i++;
            }
        }
        else {
            if (s[i + 1] == ' ' || s[i + 1] == '\0') {
                reverseWord(s, start, i);
                findStart = true;
            }
            i++;
        }
    }
    return s;
}

void reverseWord(char* s, int start, int end) {
    while (start < end) {
        char tmp = s[start];
        s[start] = s[end];
        s[end] = tmp;

        start++;
        end--;
    }
}

2.Reverse String II (Easy 541)

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Note:
1.The string consists of lower English letters only.
2.Length of the given string and k will in the range [1, 10000]
Solution:

char* reverseStr(char* s, int k) {
    int length = strlen(s);

    bool reverse = true;
    for (int i = 0; i * k < length; i++) {
        if (!reverse) {
            reverse = true;
            continue;
        }

        reverseFunc(s, i * k, ((i + 1) * k < length ? (i + 1) * k : length) - 1);
        reverse = false;
    }
    return s;
}

void reverseFunc(char* s, int start, int end) {
    while (start < end) {
        char tmp = s[start];
        s[start] = s[end];
        s[end] = tmp;

        start++;
        end--;
    }
}

3.Island Perimeter (Easy 463)

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Example:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Answer: 16

Solution:

int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {
    int perimeter = 0;
    for (int i = 0; i < gridRowSize; i++) {
        for (int j = 0; j < gridColSize; j++) {
            if (!grid[i][j]) continue;
            if (i == 0 || grid[i - 1][j] == 0) perimeter++;
            if (i == gridRowSize - 1 || grid[i + 1][j] == 0) perimeter++;
            if (j == 0 || grid[i][j - 1] == 0) perimeter++;
            if (j == gridColSize - 1 || grid[i][j + 1] == 0) perimeter++;
        }
    }
    return perimeter;
}

4.Complex Number Multiplication (Medium 537)

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i * i = -1 according to the definition.
Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i * i + 2 * i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i * i - 2 * i = -2i, and you need convert it to the form of 0+-2i.

Solution:

char* complexNumberMultiply(char* a, char* b) {
    int x1, y1, x2, y2;
    parse(a, &x1, &y1);
    parse(b, &x2, &y2);

    int resultX = x1 * x2 - y1 * y2;
    int resultY = x1 * y2 + x2 * y1;

    // magic num, haha
    char* result = (char*)malloc(sizeof(char) * 20);
    int index = 0;

    // reverse order
    result[index++] = 'i';
    addResult(result, &index, resultY);
    result[index++] = '+';
    addResult(result, &index, resultX);
    result[index] = 0;

    // reverse
    int x = 0, y = index - 1;
    while(x < y) {
        char tmp = result[x];
        result[x] = result[y];
        result[y] = tmp;
        x++;
        y--;
    }

    return result;
}

void addResult(char* result, int* index, int num) {
    int tmp = num >= 0 ? num : num * -1;
    if (tmp == 0) {
        result[(*index)++] = '0';
    }
    else {
        while(tmp) {
            result[(*index)++] = tmp % 10 + '0';
            tmp /= 10;
        }
        if (num < 0) {
            result[(*index)++] = '-';
        }
    }
}

void parse(char* s, int* x, int* y) {
    int length = strlen(s);
    int pos = -1;
    for (int i = 0; i < length; i++) {
        if (s[i] == '+') {
            pos = i;
            break;
        }
    }

    *x = toNum(s, 0, pos - 1);
    *y = toNum(s, pos + 1, length - 2);
}

int toNum(char *s, int start, int end) {
    int factor = 1;
    if (s[start] == '-') {
        start++;
        factor = -1;
    }

    int result = 0;
    for (int i = start; i <= end; i++) {
        result = result * 10 + s[i] - '0';
    }
    return result * factor;
}

5.Battleships in a Board (Medium 419)

Given an 2D board, count how many battleships are in it. The battleships are represented with ‘X’s, empty slots are represented with ‘.’s. You may assume the following rules:

1.You receive a valid board, made of only battleships or empty slots.
2.Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
3.At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example 1:

X..X
...X
...X

In the above board there are 2 battleships.
Example 2:

...X
XXXX
...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

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.Counting Bits (Medium 338)

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:

For num = 5 you should return [0,1,1,2,1,2].

Follow up:
1.It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
2.Space complexity should be O(n).
3.Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int num, int* returnSize) {
    int* result = (int*)malloc(sizeof(int) * (num + 1));
    *returnSize = num + 1;
    // init first member
    result[0] = 0;

    int cubeNum = 1;
    for (int i = 1; i <= num; i++) {
        if (i >= cubeNum * 2) {
            cubeNum *= 2;
        }
        result[i] = 1 + result[i - cubeNum];
    }

    return result;
}

7.Ugly Number II (Medium 264)

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

Solution:

int nthUglyNumber(int n) {
    if (n <= 0) return 1;
    int* result = (int*)malloc(sizeof(int) * n);
    result[0] = 1;
    int factor2 = 0, factor3 = 0, factor5 = 0;

    for (int i = 1; i < n; i++) {
        result[i] = findMin(result[factor2] * 2, result[factor3] * 3, result[factor5] * 5);

        if (result[i] == result[factor2] * 2) factor2++;
        if (result[i] == result[factor3] * 3) factor3++;
        if (result[i] == result[factor5] * 5) factor5++;
    }

    return result[n - 1];
}

int findMin(int x, int y, int z) {
    return x <= (y <= z ? y : z) ? x : (y <= z ? y : z);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LeetCode Week 4 的相关文章

  • 图像相似度计算之直方图方法OpenCV实现

    操作步骤 1 载入图像 灰度图或者彩色图 并使其大小一致 2 若为彩色图 增进行颜色空间变换 从RGB转换到HSV 若为灰度图则无需变换 3 若为灰度图 直接计算其直方图 并进行直方图归一化 4 若为彩色图 则计算其彩色直方图 并进行彩色直
  • HTTP首部(下)

    开始头大 哈哈 这个东西真的很无聊且枯燥 奈何最近的学习中经常用到这些知识 还是过一遍比较放心 上一篇博客中我们讨论了http报文首部 其划分为请求头和响应头 请求头主要由请求行 请求字段 通用字段 实体字段组成 那么响应头也由响应行 响应

随机推荐

  • go hash中的读写操作

    在 Go 语言中 我们可以使用 for 循环来遍历哈希表 hash 中的键值对 针对不同的操作进行读写操作 示例代码如下 创建一个映射类型的哈希表 hash map string int apple 2 banana 3 orange 4
  • uni-app实现PDA采集器扫码

    uni app实现PDA采集器扫码 一 开发建议 1 建议使用nvue开发 体检会非常好 使用uni preloadPage url pages index 预加载页面 页面的流畅程度会提高非常多 单独vue的写法 打包成安卓体验很不好 模
  • IntelliJ IDEA 编译程序出现非法字符的解决方法

    最近编码完成后总是报非法字符 项目启动不起来 网上有很多说是File gt Setting gt File Encoding 将IDE Encoding和Project Encoding 都设置为UTF 8就行 可是我试了不行 后来看到另外
  • 不会把if-else重构成高质量代码的程序员,不是个优秀的程序员

    为什么我们写的代码都是 if else 程序员想必都经历过这样的场景 刚开始自己写的代码很简洁 逻辑清晰 函数精简 没有一个 if else 可随着代码逻辑不断完善和业务的瞬息万变 比如需要对入参进行类型和值进行判断 这里要判断下对象是否为
  • 3、backbone中的model实例

    关于backbone 最基础的一个东西就是model 这个东西就像是后端开发中的数据库映射那个model一样 也是数据对象的模型 并且应该是和后端的model有相同的属性 仅是需要通过前端来操作的属性 下面就从实例来一步一步的带大家来了解b
  • 文心一言、讯飞星火与GPT-4/3.5在回答中文历史问题的表现

    最近 随着备受关注的文心一言正式免费向全社会开放 再次引起了社会层面对国产大模型的兴趣 以文心一言为代表的国产大模型性能究竟如何 如果将它们相互比较 并且和GPT系列模型等国际前沿水平的LLM进行比较 会得到什么样的结果呢 笔者对此非常好奇
  • Python所有方向的学习路线图

    在放这个路线图之前 我先做一个简单的介绍 避免新手小白有什么不理解的 这个学习路线上面写的是某个方向建议学习和掌握的知识带你 这样学习下来之后会更加容易掌握 知识体系会比较全面 比自己单纯的自学效果好很多 不至于看到什么就学什么 容易走弯路
  • 二,ES6中新增const关键字的使用方法

    之前用var声明变量 变量想怎么改就怎么改 这里const关键字也是声明变量的 不过声明的是常量 常量就是固定的一个值 不能改变 例如 const name 唐僧 name 老沙 报错 因为它要更改常量name 只在块级作用于起作用 和le
  • Windows10 java环境变量的配置详细教程(Windows10 和Windows11)

    java环境变量的配置详细教程 1 首先要区分一下Windows10 2021年之前的版本和Windows10 2021年之后的版本 Windows10 2021年之后的版本和Windows11 系统在配置java上差不多 故不作区分 1
  • Intellij IDEA svn的使用记录

    这里的忽略一直灰色的 可以进入 这里的版本控制里进行忽略选择 或者 这里进行添加 这里有三个选择 按照顺序 1 忽略指定的文件 2 忽略文件夹下所有文件 3 忽略符合匹配规则的文件 到Commit Changes 这里有几个选项需要了解的
  • Vue实例挂载的过程

    一 思考与分析 我们都听过知其然知其所以然这句话 那么不知道是否思考过new Vue 这个过程中究竟做了些什么 过程中是如何完成数据的绑定 又是如何将数据渲染到视图的等等 首先找到vue的构造函数 源码位置 src core instanc
  • 因为强行关机, 而导致的fedora23 不能重新启动, 卡在开机logo那里的 修复 解决方案...

    其实 fedora23的U盘live 也很好用 很流畅 主要还是 要用一个比较好的 快的 U盘 这样live U盘在4GB 3 75GiB 的内存中还是较快的 原来的U盘live系统用得很卡 可能是因为 U盘太烂的原因 要方便的使用live
  • SAXParserFactoryImpl cast SAXParserFactory异常

    Caused by java lang ClassCastException com sun org apache xerces internal jaxp SAXParserFactoryImpl cannot be cast to ja
  • web攻击日志分析之新手指

    0x00 前言 现实中可能会经常出现web日志当中出现一些被攻击的迹象 比如针对你的一个站点的URL进行SQL注入测试等等 这时候需要你从日志当中分析到底是个什么情况 如果非常严重的话 可能需要调查取证谁来做的这个事情 攻击流程是什么样子的
  • AlibabaProtect 卸载,不使用其他软件

    背景 发现系统中存在AlibabaProtect服务 停止不掉 文件夹也删除不掉 还占用内存 CPU 在网上也搜了很多其他的步骤 发现不太容易 这是整理的比较简单的 不需要装其他软件 步骤 1 删除注册表 AlibabaProtect搜索之
  • 华为OD机试-最长连续方波信号

    Online C compiler to run C program online include
  • docker-engine安装

    最近一直在使用docker 做一些试验 每个新机器都需要部署docker的环境 环境信息如下 RedHat 7 2 安装 docker官方的安装 docker engine 1 sudo rpm import https sks keyse
  • Webpack5优化之提高代码运行性能(Preload、Network Cache、Core-js、PWA)

    文章目录 一 Preload Prefetch 1 1 为什么 1 2 是什么 1 2 1 共同点 1 2 2 区别 1 2 3 问题 1 2 4 总结 1 3 怎么样 1 3 1 安装依赖 1 3 2 配置 1 3 3 测试 二 Netw
  • python获取微信群消息_python-itchat 统计微信群、好友数量,及原始消息数据的实例...

    coding utf 8 import itchat from itchat content import TEXT from itchat content import import sys import time import re r
  • LeetCode Week 4

    LeetCode Week 4 练腿是最虐的项目 没有之一 问题集合 1 Reverse Words in a String III Easy 557 Given a string you need to reverse the order