Leetcode在线课程 - 算法基础 - 数组/字符串

关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers

Leetcode上有一门很小的在线课程,叫算法基础(Algorithm Basics),包括文章讲解与算法题。
我花了一个周末阅读及做题,也算是对本科知识的一个复习吧。内容及题目都不难,我就不做翻译了。

第一章:数组/字符串

two-pointer-technique 双指针方法

One slow-runner and the other fast-runner.
或者
One pointer starts from the beginning while the other pointer starts from the end.

Remove Duplicates from Sorted Array 从排序数组中删除重复元素 直达Leetcode

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,Given input array nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

int removeDuplicates(int* nums, int numsSize) {
    if(numsSize <= 1) {
        return numsSize;
    }
    
    // Two pointer method
    int p1 = 0;
    int p2 = 1;
    
    while(p1 < numsSize && p2 < numsSize) {
        // Duplicates
        if(nums[p1] == nums[p2]) {
            p2++;
        } else {
            p1++;
            nums[p1] = nums[p2];
            p2++;
        }
    }
    
    return p1 + 1;
}

Two Sum II – Input array is sorted 有序数组,找到两个元素使得相加结果为指定值 直达Leetcode

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.

/**
 * 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) {
    // Two pointer method
    int p1 = 0;
    int p2 = numbersSize - 1;
    
    *returnSize = 2;
    int* result = (int*)malloc(sizeof(int) * (*returnSize));
    
    while(p1 < p2) {
        if(numbers[p1] + numbers[p2] > target) {
            p2--;
        }
        
        else if(numbers[p1] + numbers[p2] < target) {
            p1++;
        }
        
        else {
            result[0] = p1 + 1;
            result[1] = p2 + 1;
            break;
        }
    }
    
    return result;
}

Hash Table 使用Hash表记录出现次数

Valid Anagram 判断两个字符串是否共享字母 直达Leetcode

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,s = “anagram”, t = “nagaram”, return true.s = “rat”, t = “car”, return false.

bool isAnagram(char* s, char* t) {
    if(strlen(s) != strlen(t)) {
        return false;
    }
    
    int m[256] = {0};
    for(int i = 0; i < strlen(s); i++) {
        m[s[i]] = m[s[i]] + 1;
        m[t[i]] = m[t[i]] - 1;
    }
    
    for(int i = 0; i < 256; i++) {
        if(m[i] != 0)
            return false;
    }
    
    return true;
}

Longest Substring Without Repeating Characters 无重复字母的最长子序列 直达Leetcode

Given a string, find the length of the longest substring without repeating characters.
Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

int lengthOfLongestSubstring(char* s) {
    if(strlen(s) == 0) {
        return 0;
    }
    
    if(strlen(s) == 1) {
        return 1;
    }
    
    int m[256];
    for(int i = 0; i < 256; i++) {
        m[i] = -1;
    }
    
    int max = 0;
    int start = -1;
    for(int i = 0; i < strlen(s); i++) {
        if (m[s[i]] > start) {
            start = m[s[i]];
        }
        m[s[i]] = i;
        
        max = (max > (i - start) ? max : (i - start));
    }
    
    return max;
}

String Manipulation 字符串操作

Implement strStr() 查找子串 使用标准KMP算法 直达Leetcode

void compute_next(char* s, int* next) {
    next[0] = 0;
    
    int k;
    for(int i = 1; i < strlen(s); i++) {
        // Compute next[i]
        k = next[i - 1];
        
        while(s[k] != s[i] && k > 0) {
            k = next[k - 1];
        }
        
        if(s[k] == s[i]) {
            next[i] = k + 1;
        }
        else {
            next[i] = 0;
        }
    }
}

int strStr(char* haystack, char* needle) {
    if(strlen(haystack) < strlen(needle)) {
        return -1;
    }
    
    if(strlen(needle) == 0) {
        return 0;
    }
    
    int* next = (int*)malloc(sizeof(int) * strlen(needle));
    compute_next(needle, next);
    
    int i = 0, j = 0;
    while(i < strlen(haystack) && j < strlen(needle)) {
        if(haystack[i] == needle[j]) {
            i++;
            j++;
        }
        else {
            // i = i - j + 1;
            // j = 0;
            if(j == 0) {
                i++;
            }
            else {
                j = next[j - 1];   
            }
        }
    }
    
    if(j == strlen(needle)) {
        return i - strlen(needle); 
    }
    
    return -1;
}

String to Integer (atoi) 查找子串 使用标准KMP算法 直达Leetcode

  int atoi(const char *str) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(str == NULL)
            return 0;
        
        int i = 0;
        while(str[i] != '\0' && str[i] == ' ')
        {
            i++;
        }
        
        // Positive or negative
        bool positive = true;
        if(str[i] == '-')
        {
            positive = false;
            i++;
        }
        if(str[i] == '+')
        {
             positive = true;
             i++;
        }
        
        long long ret = 0;
        
        while(isdigit(str[i]))
        {
            ret = ret * 10 + (str[i] - '0');
            i++;
        }
        
        if(positive == false)
            ret = 0 - ret;
            
        if(ret < INT_MIN)
            return INT_MIN;
        else if(ret > INT_MAX)
            return INT_MAX;
        else
            return ret;
    }

引用:
https://leetcode.com/courses/chapters/1

    原文作者:专职跑龙套
    原文地址: https://www.jianshu.com/p/198d4fb0d6da
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞