數據結構丨數組和字符串


數組簡介

數組簡介

數組是一種基本的數據結構,用於按順序存儲元素的集合。但是元素可以隨機存取,因為數組中的每個元素都可以通過數組索引來識別。

數組可以有一個或多個維度。這里我們從一維數組開始,它也被稱為線性數組。這里有一個例子:

img

在上面的例子中,數組 A 中有 6 個元素。也就是說,A 的長度是 6 。我們可以使用 A[0] 來表示數組中的第一個元素。因此,A[0] = 6 。類似地,A[1] = 3,A[2] = 8,依此類推。

數組中的操作

讓我們來看看數組的用法:

#include <iostream>

int main() {
    // 1. Initialize
    int a0[5];
    int a1[5] = {1, 2, 3};  // other element will be set as the default value
    // 2. Get Length
    int size = sizeof(a1) / sizeof(*a1);
    cout << "The size of a1 is: " << size << endl;
    // 3. Access Element
    cout << "The first element is: " << a1[0] << endl;
    // 4. Iterate all Elements
    cout << "[Version 1] The contents of a1 are:";
    for (int i = 0; i < size; ++i) {
        cout << " " << a1[i];
    }
    cout << endl;
    cout << "[Version 2] The contents of a1 are:";
    for (int& item: a1) {
        cout << " " << item;
    }
    cout << endl;
    // 5. Modify Element
    a1[0] = 4;
    // 6. Sort
    sort(a1, a1 + size);
}

動態數組

正如我們在上一篇文章中提到的,數組具有固定的容量,我們需要在初始化時指定數組的大小。有時它會非常不方便並可能造成浪費。

因此,大多數編程語言都提供內置的動態數組,它仍然是一個隨機存取的列表數據結構,但大小是可變的。例如,在 C++ 中的 vector,以及在 Java 中的 ArrayList

動態數組中的操作

讓我們來看看動態數組的用法:

#include <iostream>

int main() {
    // 1. initialize
    vector<int> v0;
    vector<int> v1(5, 0);
    // 2. make a copy
    vector<int> v2(v1.begin(), v1.end());
    vector<int> v3(v2);
    // 2. cast an array to a vector
    int a[5] = {0, 1, 2, 3, 4};
    vector<int> v4(a, *(&a + 1));
    // 3. get length
    cout << "The size of v4 is: " << v4.size() << endl;
    // 4. access element
    cout << "The first element in v4 is: " << v4[0] << endl;
    // 5. iterate the vector
    cout << "[Version 1] The contents of v4 are:";
    for (int i = 0; i < v4.size(); ++i) {
        cout << " " << v4[i];
    }
    cout << endl;
    cout << "[Version 2] The contents of v4 are:";
    for (int& item : v4) {
        cout << " " << item;
    }
    cout << endl;
    cout << "[Version 3] The contents of v4 are:";
    for (auto item = v4.begin(); item != v4.end(); ++item) {
        cout << " " << *item;
    }
    cout << endl;
    // 6. modify element
    v4[0] = 5;
    // 7. sort
    sort(v4.begin(), v4.end());
    // 8. add new element at the end of the vector
    v4.push_back(-1);
    // 9. delete the last element
    v4.pop_back();
}

尋找數組的中心索引

給定一個整數類型的數組 nums,請編寫一個能夠返回數組“中心索引”的方法。

我們是這樣定義數組中心索引的:數組中心索引的左側所有元素相加的和等於右側所有元素相加的和。

如果數組不存在中心索引,那么我們應該返回 -1。如果數組有多個中心索引,那么我們應該返回最靠近左邊的那一個。

示例 1:

輸入: 
nums = [1, 7, 3, 6, 5, 6]
輸出: 3
解釋: 
索引3 (nums[3] = 6) 的左側數之和(1 + 7 + 3 = 11),與右側數之和(5 + 6 = 11)相等。
同時, 3 也是第一個符合要求的中心索引。

示例 2:

輸入: 
nums = [1, 2, 3]
輸出: -1
解釋: 
數組中不存在滿足此條件的中心索引。

說明:

  • nums 的長度范圍為 [0, 10000]
  • 任何一個 nums[i] 將會是一個范圍在 [-1000, 1000]的整數。
class Solution{
public:
    int pivotIndex(vector<int>& nums){
        if(nums.size() == 0)
            return -1;
        int sum = accumulate(nums.begin(), nums.end(), 0);

        int leftSum = 0;
        for(int i=0; i<nums.size(); i++)
            if(leftSum == sum-leftSum-nums[i])
                return i;
            else 
                leftSum += nums[i];
        
        return -1;
    }
};

至少是其他數字兩倍的最大數

在一個給定的數組nums中,總是存在一個最大元素 。

查找數組中的最大元素是否至少是數組中每個其他數字的兩倍。

如果是,則返回最大元素的索引,否則返回-1。

示例 1:

輸入: nums = [3, 6, 1, 0]
輸出: 1
解釋: 6是最大的整數, 對於數組中的其他整數,
6大於數組中其他元素的兩倍。6的索引是1, 所以我們返回1.

示例 2:

輸入: nums = [1, 2, 3, 4]
輸出: -1
解釋: 4沒有超過3的兩倍大, 所以我們返回 -1.

提示:

  1. nums 的長度范圍在[1, 50].
  2. 每個 nums[i] 的整數范圍在 [0, 99].
#include <iostream>
#include <vector>

using namespace std;

/// Linear Scan
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution{
public:
    int dominantIndex(vector<int>& nums){
        int maxNum = *max_element(nums.begin(), nums.end());
        int res = -1;
        for(int i = 0; i< nums.size(); i++)
            if(nums[i] != maxNum){
                if(maxNum < 2*nums[i])
                    return -1;
            }
            else
                res = i;
        return res;
    }
};

加一

給定一個由整數組成的非空數組所表示的非負整數,在該數的基礎上加一。

最高位數字存放在數組的首位, 數組中每個元素只存儲一個數字。

你可以假設除了整數 0 之外,這個整數不會以零開頭。

示例 1:

輸入: [1,2,3]
輸出: [1,2,4]
解釋: 輸入數組表示數字 123。

示例 2:

輸入: [4,3,2,1]
輸出: [4,3,2,2]
解釋: 輸入數組表示數字 4321。
#include <iostream>
#include <vector>

using namespace std;

/// Ad Hoc
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution{
public:
    vector<int> plusOne(vector<int>& digits){
        digits[digits.size() -1] ++;
        for(int i=digits.size()-1; i>=1; i--)
            if(digits[i] == 10){
                digits[i] = 0;
                digits[i-1] ++;
            }
        if(digits[0] == 10){
            digits[0] = 0;
            digits.insert(digits.begin(), 1);
        }
        return digits;
    }
}

二維數組簡介

二維數組簡介

類似於一維數組,二維數組也是由元素的序列組成。但是這些元素可以排列在矩形網格中而不是直線上。

示例

#include <iostream>

template <size_t n, size_t m>
void printArray(int (&a)[n][m]) {
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    cout << "Example I:" << endl;
    int a[2][5];
    printArray(a);
    cout << "Example II:" << endl;
    int b[2][5] = {{1, 2, 3}};
    printArray(b);
    cout << "Example III:"<< endl;
    int c[][5] = {1, 2, 3, 4, 5, 6, 7};
    printArray(c);
    cout << "Example IV:" << endl;
    int d[][5] = {{1, 2, 3, 4}, {5, 6}, {7}};
    printArray(d);
}

原理

在一些語言中,多維數組實際上是在內部作為一維數組實現的,而在其他一些語言中,實際上根本沒有多維數組

1. C++ 將二維數組存儲為一維數組。

下圖顯示了大小為 M * N 的數組 A 的實際結構:

img

2. 在Java中,二維數組實際上是包含着 M 個元素的一維數組,每個元素都是包含有 N 個整數的數組。

下圖顯示了 Java 中二維數組 A 的實際結構:

img

動態二維數組

與一維動態數組類似,我們也可以定義動態二維數組。 實際上,它可以只是一個嵌套的動態數組。 你可以自己嘗試一下。

對角線遍歷

給定一個含有 M x N 個元素的矩陣(M 行,N 列),請以對角線遍歷的順序返回這個矩陣中的所有元素,對角線遍歷如下圖所示。

示例:

輸入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

輸出:  [1,2,4,7,5,3,6,8,9]

解釋:

img

說明:

  1. 給定矩陣中的元素總數不會超過 100000 。
#include <iostream>
#include <vector>

using namespace std;

/// Simulation
/// Time Complexity: O(n * m)
/// Space Complexity: O(1)
class Solution
{
private:
    int n, m;

public:
    vector<int> findDiagonalOrder(vector<vector<int>> &matrix)
    {
        vector<int> res;

        n = matrix.size();
        if (n == 0)
            return res;
        m = matrix[0].size();

        int x = 0, y = 0;
        int nextX, nextY;
        bool up = true;
        while (true)
        {
            res.push_back(matrix[x][y]);

            if (up)
                nextX = x - 1, nextY = y + 1;
            else
                nextX = x + 1, nextY = y - 1;
            
            if(inArea(nextX, nextY))
                x = nextX, y = nextY;
            else if(up){
                if(inArea(x, y+1))
                    y++;
                else
                    x++;
                up = false;
            }
            else{
                if(inArea(x+1, y))
                    x++;
                else
                    y++;
                up = true;
            }
            if(!inArea(x, y))
                break;
        }
        return res;
    }
private:
    bool inArea(int x, int y){
        return x>=0 && x<n && y >=0 && y<m;
    }
};

void print_vec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main(){
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}};
    
    print_vec(Solution().findDiagonalOrder(matrix));

    return 0;
}

螺旋矩陣

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例 1:

輸入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]

示例 2:

輸入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]
/// Source : https://leetcode.com/problems/spiral-matrix/description/
/// Author : liuyubobobo
/// Time   : 2018-04-24

#include <iostream>
#include <vector>

using namespace std;


/// Simulation
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {

private:
    int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int N, M;

public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {

        N = matrix.size();
        if(N == 0)
            return {};

        M = matrix[0].size();
        if(M == 0)
            return {};

        vector<vector<bool>> visited(N, vector<bool>(M, false));
        int curd = 0, curx = 0, cury = 0;
        vector<int> res;
        while(res.size() < N * M){

            if(!visited[curx][cury]) {
                res.push_back(matrix[curx][cury]);
                visited[curx][cury] = true;
            }

            int nextx = curx + d[curd][0];
            int nexty = cury + d[curd][1];
            if(inArea(nextx, nexty) && !visited[nextx][nexty]){
                curx = nextx;
                cury = nexty;
            }
            else
                curd = (curd + 1) % 4;
        }
        return res;
    }

private:
    bool inArea(int x, int y){
        return x >= 0 && x < N && y >= 0 && y < M;
    }
};


void print_vec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    vector<vector<int>> matrix1 = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
    };
    print_vec(Solution().spiralOrder(matrix1));

    return 0;
}

楊輝三角

給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。

img

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 5
輸出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
#include <iostream>
#include <vector>

using namespace std;

/// Simulation (Dynamic Programming)
/// Time Complexity: O(n^2)
/// Space Complexity: O(1)
class Solution{
public:
    vector<vector<int>> generate(int numRows){
        vector<vector<int>> res;
        if(numRows <= 0)
            return res;
        res.push_back({1});
        for(int i=1; i<numRows; i++){
            vector<int> row;
            row.push_back(1);
            for(int j=1; j<i; j++)
                row.push_back(res[i-1][j-1]+res[i-1][j]);
            row.push_back(1);
            res.push_back(row);
        }
        return res;
    }
};

字符串簡介

字符串簡介

字符串實際上是一個 unicode 字符數組。你可以執行幾乎所有我們在數組中使用的操作,自己試試看吧。

然而,二者之間還是存在一些區別。在這篇文章中,我們將介紹一些在處理字符串時應該注意的問題。這些特性在不同的語言之間可能有很大不同。

比較函數

字符串有它自己的比較函數(我們將在下面的代碼中向你展示比較函數的用法)。

然而,存在這樣一個問題:

我們可以用 “==” 來比較兩個字符串嗎?

這取決於下面這個問題的答案:

我們使用的語言是否支持運算符重載

  1. 如果答案是 yes (例如 C++)。我們可以使用 “==” 來比較兩個字符串。
  2. 如果答案是 no (例如 Java),我們可能無法使用” 來比較兩個字符串。當我們使用 “” 時,它實際上會比較這兩個對象是否是同一個對象。

讓我們運行下面的例子並比較結果:

#include <iostream>

int main() {
    string s1 = "Hello World";
    cout << "s1 is \"Hello World\"" << endl;
    string s2 = s1;
    cout << "s2 is initialized by s1" << endl;
    string s3(s1);
    cout << "s3 is initialized by s1" << endl;
    // compare by '=='
    cout << "Compared by '==':" << endl;
    cout << "s1 and \"Hello World\": " << (s1 == "Hello World") << endl;
    cout << "s1 and s2: " << (s1 == s2) << endl;
    cout << "s1 and s3: " << (s1 == s3) << endl;
    // compare by 'compare'
    cout << "Compared by 'compare':" << endl;
    cout << "s1 and \"Hello World\": " << !s1.compare("Hello World") << endl;
    cout << "s1 and s2: " << !s1.compare(s2) << endl;
    cout << "s1 and s3: " << !s1.compare(s3) << endl;
}

是否可變

不可變意味着一旦字符串被初始化,你就無法改變它的內容。

  1. 在某些語言(如 C ++)中,字符串是可變的。 也就是說,你可以像在數組中那樣修改字符串。
  2. 在其他一些語言(如 Java)中,字符串是不可變的。 此特性將帶來一些問題。 我們將在下一篇文章中闡明問題和解決方案。

你可以通過測試修改操作來確定你喜歡的語言中的字符串是否可變。這里有一個示例:

#include <iostream>

int main() {
    string s1 = "Hello World";
    s1[5] = ',';
    cout << s1 << endl;
}

額外操作

與數組相比,我們可以對字符串執行一些額外的操作。這里有一些例子:

#include <iostream>

int main() {
    string s1 = "Hello World";
    // 1. concatenate
    s1 += "!";
    cout << s1 << endl;
    // 2. find
    cout << "The position of first 'o' is: " << s1.find('o') << endl;
    cout << "The position of last 'o' is: " << s1.rfind('o') << endl;
    // 3. get substr
    cout << s1.substr(6, 5) << endl;
}

你應該了解這些內置操作的時間復雜度。

例如,如果字符串的長度是 N,那么查找操作和子字符串操作的時間復雜度是 O(N)

此外,在字符串不可變的語言中,你應該額外小心連接操作(我們將在下一篇文章中解釋這一點)。

在計算解決方案的時間復雜度時,不要忘記考慮內置操作的時間復雜度。

不可變字符串 —— 問題和解決方案

在上一篇文章中,您應該已經知道您喜歡的語言中的字符串是否為不可變的。如果字符串是不可變的,則會帶來一些問題。希望我們也能在最后提供解決方案。

修改操作

顯然,不可變字符串無法被修改。哪怕你只是想修改其中的一個字符,也必須創建一個新的字符串。

小心Java中的字符串

你應該非常小心字符串連接。讓我們來看一個在 for 循環中重復進行字符串連接的例子:

#include <iostream>

int main() {
    string s = "";
    int n = 10000;
    for (int i = 0; i < n; i++) {
        s += "hello";
    }
}

請注意對於 Java 來說字符串連接有多慢? 另一方面,在 C++ 中沒有明顯的性能影響。

在 Java 中,由於字符串是不可變的,因此在連接時首先為新字符串分配足夠的空間,復制舊字符串中的內容並附加到新字符串。

因此,總時間復雜度將是:

5 + 5 × 2 + 5 × 3 + … + 5 × n
= 5 × (1 + 2 + 3 + … + n)
= 5 × n × (n + 1) / 2,

也就是 O(n2)

解決方案

如果你希望你的字符串是可變的,這里有一些替代方案:

1. 如果你確實希望你的字符串是可變的,則可以將其轉換為字符數組。

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        String s = "Hello World";
        char[] str = s.toCharArray();
        str[5] = ',';
        System.out.println(str);
    }
}

2. 如果你經常必須連接字符串,最好使用一些其他的數據結構,如 StringBuilder 。 以下代碼以 O(n) 的復雜度運行。

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        int n = 10000;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < n; i++) {
            str.append("hello");
        }
        String s = str.toString();
    }
}

二進制求和

給定兩個二進制字符串,返回他們的和(用二進制表示)。

輸入為非空字符串且只包含數字 10

示例 1:

輸入: a = "11", b = "1"
輸出: "100"

示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"
/// Source : https://leetcode.com/problems/add-binary/description/
/// Author : liuyubobobo
/// Time   : 2018-06-03

#include <iostream>

using namespace std;

/// Simulation
/// Time Complexity: O(max(len(a), len(b)))
/// Space Complexity: O(1)
class Solution {
public:
    string addBinary(string a, string b) {

        string res = a.size() > b.size() ? a : b;
        string adder = a.size() > b.size() ? b : a;

        int index = res.size() - 1;
        for(int i = adder.size() - 1 ; i >= 0 ; i --){
            res[index] += adder[i] - '0';
            index --;
        }

        for(int i = res.size() - 1 ; i > 0 ; i --)
            if(res[i] > '1'){
                res[i - 1] += 1;
                res[i] = '0' + (res[i] - '0') % 2;
            }

        if(res[0] > '1'){
            res[0] = '0' + (res[0] - '0') % 2;
            res = '1' + res;
        }
        return res;
    }
};


int main() {

    cout << Solution().addBinary("11", "1") << endl;
    cout << Solution().addBinary("1010", "1011") << endl;

    return 0;
}

實現strStr()

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2

示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1

說明:

needle 是空字符串時,我們應當返回什么值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

#include <iostream>

using namespace std;

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        if (needle.size() > haystack.size())
            return -1;
        for(int i = 0 ; i <= haystack.size() - needle.size() ; i ++){
            int j = 0;
            for(j = 0 ; j < needle.size() ; j ++)
                if(needle[j] != haystack[j + i])
                    break;
            if(j == needle.size())
                return i;
        }
        return -1;
}
};

int main() {

    cout << Solution().strStr("hello", "ll") << endl;
    cout << Solution().strStr("aaaaa", "bba") << endl;

    return 0;
}

最長公共前綴

編寫一個函數來查找字符串數組中的最長公共前綴。

如果不存在公共前綴,返回空字符串 ""

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"

示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。

說明:

所有輸入只包含小寫字母 a-z

#include <iostream>

using namespace std;

/// Vertical Scan
/// Time Complexity: O(len(strs) * max len of string)
/// Space Complexity: O(1)
class Solution{
public: 
    string longestCommonPrefix(vector<string>& strs){
        string res = "";
        if(strs.size()==0)
            return res;
        
        for(int i=0; i<strs[0].size(); i++){
            char c = strs[0][[i];
            for(int j=1; j<strs.size(); j++)
                if(i >= strs[j].size() || strs[j][i] != c)
                    return res;
            res += c;
        }
        return res;
    }
};

int main() {

    vector<string> strs1 = {"flower","flow","flight"};
    cout << Solution().longestCommonPrefix(strs1) << endl;

    vector<string> strs2 = {"dog","racecar","car"};
    cout << Solution().longestCommonPrefix(strs2) << endl;

    return 0;
}

雙指針技巧

雙指針技巧 —— 情景一

在前一章中,我們通過迭代數組來解決一些問題。通常,我們只使用從第一個元素開始並在最后一個元素結束的一個指針來進行迭代。 但是,有時候,我們可能需要同時使用兩個指針來進行迭代。

示例

讓我們從一個經典問題開始:

反轉數組中的元素。

其思想是將第一個元素與末尾進行交換,再向前移動到下一個元素,並不斷地交換,直到它到達中間位置。

我們可以同時使用兩個指針來完成迭代:一個從第一個元素開始,另一個從最后一個元素開始。持續交換它們所指向的元素,直到這兩個指針相遇。

以下代碼可以供你參考:

void reverse(int *v, int N) {
    int i = 0;
    int j = N - 1;
    while (i < j) {
        swap(v[i], v[j]);
        i++;
        j--;
    }
}

總結

總之,使用雙指針技巧的典型場景之一是你想要

從兩端向中間迭代數組。

這時你可以使用雙指針技巧:

一個指針從始端開始,而另一個指針從末端開始。

值得注意的是,這種技巧經常在排序數組中使用。

反轉字符串

編寫一個函數,其作用是將輸入的字符串反轉過來。輸入字符串以字符數組 char[] 的形式給出。

不要給另外的數組分配額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。

你可以假設數組中的所有字符都是 ASCII 碼表中的可打印字符。

示例 1:

輸入:["h","e","l","l","o"]
輸出:["o","l","l","e","h"]

示例 2:

輸入:["H","a","n","n","a","h"]
輸出:["h","a","n","n","a","H"]
#include <iostream>
#include <vector>
using namespace std;

/// Two Pointers
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution{
public: 
    void reverseString(vector<char>& s){
        int i=0, j=s.size()-1;
        while(i<j){
            swap(s[i], s[j]);
            i ++;
            j --;
        }
    }
};

數組拆分I

給定長度為 2n 的數組, 你的任務是將這些數分成 n 對, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得從1 到 n 的 min(ai, bi) 總和最大。

示例 1:

輸入: [1,4,3,2]

輸出: 4
解釋: n 等於 2, 最大總和為 4 = min(1, 2) + min(3, 4).

提示:

  1. n 是正整數,范圍在 [1, 10000].
  2. 數組中的元素范圍在 [-10000, 10000].

#include <iostream>
#include <vector>

using namespace std;

/// Sort
/// Time Complexity: O(nlogn)
/// Space Complexity: O(1)
class Solution {
public:
    int arrayPairSum(vector<int>& nums){
        sort(nums.begin(), nums.end());
        int sum = 0;
        for(int i=0; i<nums.size(); i+=2)
            sum+=nums[i];
        return sum;
    }
};

兩數之和 II - 輸入有序數組

給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。

函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2

說明:

  • 返回的下標值(index1 和 index2)不是從零開始的。
  • 你可以假設每個輸入只對應唯一的答案,而且你不可以重復使用相同的元素。

示例:

輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。
#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

// Two Pointers
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {

public:
    vector<int> twoSum(vector<int>& numbers, int target) {

        assert(numbers.size() >= 2);
        // assert(isSorted(numbers));

        int l = 0, r = numbers.size() - 1;
        while(l < r){

            if(numbers[l] + numbers[r] == target){
                int res[2] = {l+1, r+1};
                return vector<int>(res, res+2);
            }
            else if(numbers[l] + numbers[r] < target)
                l ++;
            else // numbers[l] + numbers[r] > target
                r --;
        }

        throw invalid_argument("the input has no solution");
    }

private:
    bool isSorted(const vector<int>& numbers){
        for(int i = 1 ; i < numbers.size() ; i ++)
            if(numbers[i] < numbers[i-1])
                return false;
        return true;
    }

};

void printVec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    int nums[] = {2, 7, 11, 15};
    vector<int> vec(nums, nums + sizeof(nums) / sizeof(int));
    int target = 9;
    printVec(Solution().twoSum(vec, target));

    return 0;
}

雙指針技巧 —— 情景二

有時,我們可以使用兩個不同步的指針來解決問題。

示例

讓我們從另一個經典問題開始:

給定一個數組和一個值,原地刪除該值的所有實例並返回新的長度。

如果我們沒有空間復雜度上的限制,那就更容易了。我們可以初始化一個新的數組來存儲答案。如果元素不等於給定的目標值,則迭代原始數組並將元素添加到新的數組中。

實際上,它相當於使用了兩個指針,一個用於原始數組的迭代,另一個總是指向新數組的最后一個位置。

重新考慮空間限制

現在讓我們重新考慮空間受到限制的情況。

我們可以采用類似的策略,我們繼續使用兩個指針:一個仍然用於迭代,而第二個指針總是指向下一次添加的位置

以下代碼可以供你參考:

int removeElement(vector<int>& nums, int val) {
    int k = 0;
    for (int i = 0; i < nums.size(); ++i) {
        if (nums[i] != val) {
            nums[k] = nums[i];
            ++k;
        }
    }
    return k;
}

在上面的例子中,我們使用兩個指針,一個快指針 i 和一個慢指針 ki 每次移動一步,而 k 只在添加新的被需要的值時才移動一步。

總結

這是你需要使用雙指針技巧的一種非常常見的情況:

同時有一個慢指針和一個快指針。

解決這類問題的關鍵是

確定兩個指針的移動策略。

與前一個場景類似,你有時可能需要在使用雙指針技巧之前對數組進行排序,也可能需要運用貪心想法來決定你的運動策略。

移除元素

給定一個數組 nums 和一個值 val,你需要原地移除所有數值等於 val 的元素,返回移除后數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。

元素的順序可以改變。你不需要考慮數組中超出新長度后面的元素。

示例 1:

給定 nums = [3,2,2,3], val = 3,

函數應該返回新的長度 2, 並且 nums 中的前兩個元素均為 2。

你不需要考慮數組中超出新長度后面的元素。

示例 2:

給定 nums = [0,1,2,2,3,0,4,2], val = 2,

函數應該返回新的長度 5, 並且 nums 中的前五個元素為 0, 1, 3, 0, 4。

注意這五個元素可為任意順序。

你不需要考慮數組中超出新長度后面的元素。

說明:

為什么返回數值是整數,但輸出的答案是數組呢?

請注意,輸入數組是以“引用”方式傳遞的,這意味着在函數里修改輸入數組對於調用者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參作任何拷貝
int len = removeElement(nums, val);

// 在函數里修改輸入數組對於調用者是可見的。
// 根據你的函數返回的長度, 它會打印出數組中該長度范圍內的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>

using namespace std;


/// Two Pointers
///Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {

public:
    int removeElement(vector<int>& nums, int val) {

        int newl = 0;
        for( int i = 0 ; i < nums.size() ; i ++ )
            if( nums[i] != val )
                nums[newl++] = nums[i];

        return newl;
    }
};


int main() {

    vector<int> nums = {3, 2, 2, 3};
    int val = 3;

    cout << Solution().removeElement(nums, val) << endl;

    return 0;
}

最大連續1的個數

給定一個二進制數組, 計算其中最大連續1的個數。

示例 1:

輸入: [1,1,0,1,1,1]
輸出: 3
解釋: 開頭的兩位和最后的三位都是連續1,所以最大連續1的個數是 3.

注意:

  • 輸入的數組只包含 01
  • 輸入數組的長度是正整數,且不超過 10,000。
#include <iostream>
#include <vector>

using namespace std;

/// Ad-Hoc
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution{
public: 
    int findMaxConsecutiveOnes(vector<int>& nums){
        int res = 0;
        int start = firstOne(nums, 0);
        for(int i=start+1; i<= nums.size(); ){
            if(i == nums.size() || nums[i] != 1){
                res = max(res, i-start);
                start = firstOne(nums, i);
                i = start + 1;
            }
            else 
                i++;
        }
        return res;
    }
private: 
    int firstOne(const vector<int>& nums, int startIndex){
        for(int i=startIndex; i<nums.size(); i++)
            if(nums[i]==1)
                return i;
        return nums.size();
    }
};

int main() {

    vector<int> nums = {1, 1, 0, 1, 1, 1};
    cout << Solution().findMaxConsecutiveOnes(nums) << endl;
    return 0;
}

長度最小的子數組

給定一個含有 n 個正整數的數組和一個正整數 s ,找出該數組中滿足其和 ≥ s 的長度最小的連續子數組如果不存在符合條件的連續子數組,返回 0。

示例:

輸入: s = 7, nums = [2,3,1,2,4,3]
輸出: 2
解釋: 子數組 [4,3] 是該條件下的長度最小的連續子數組。

進階:

如果你已經完成了O(n) 時間復雜度的解法, 請嘗試 O(n log n) 時間復雜度的解法。

#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public: 
    int minSubArrayLen(int s, vector<int>& nums){
        if (nums.size() == 0) return 0;
        int i=0, j=0, sum=0, min=INT_MAX;
        while(j<nums.size()){
            sum += nums[j++];
            while(sum >= s){
                min = (min < j-i)? min : (j-i);
                sum -= nums[i++];
            }
        }
        return min == INT_MAX? 0:min;
    }
};

小結

數組相關的技術

你可能想要了解更多與數組相關的數據結構或技術。我們不會深入研究這張卡片中的大多數概念,而是在本文中提供相應卡片的鏈接。

  1. 這里有一些其他類似於數組的數據結構,但具有一些不同的屬性:
  1. 正如我們所提到的,我們可以調用內置函數來對數組進行排序。但是,理解一些廣泛使用的排序算法的原理及其復雜度是很有用的。

  2. 二分查找也是一種重要的技術,用於在排序數組中搜索特定的元素。

  3. 我們在這一章中引入了雙指針技巧。想要靈活運用該技技巧是不容易的。這一技巧也可以用來解決:

  1. 雙指針技巧有時與貪心算法有關,它可以幫助我們設計指針的移動策略。 在不久的將來,我們會提供更多的卡片來介紹上面提到的這些技術,並更新鏈接。

旋轉數組

給定一個數組,將數組中的元素向右移動 k 個位置,其中 k 是非負數。

示例 1:

輸入: [1,2,3,4,5,6,7] 和 k = 3
輸出: [5,6,7,1,2,3,4]
解釋:
向右旋轉 1 步: [7,1,2,3,4,5,6]
向右旋轉 2 步: [6,7,1,2,3,4,5]
向右旋轉 3 步: [5,6,7,1,2,3,4]

示例 2:

輸入: [-1,-100,3,99] 和 k = 2
輸出: [3,99,-1,-100]
解釋: 
向右旋轉 1 步: [99,-1,-100,3]
向右旋轉 2 步: [3,99,-1,-100]

說明:

  • 盡可能想出更多的解決方案,至少有三種不同的方法可以解決這個問題。
  • 要求使用空間復雜度為 O(1) 的原地算法。
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

/// Using Queue
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class SolutionA {
public:
    void rotate(vector<int>& nums, int k) {

        queue<int> q;
        while(k -- && !nums.empty())
            q.push(nums.back()), nums.pop_back();
        for(int i = 0 ; i <= k ; i ++)  //if k >= nums.size()
            q.push(q.front()), q.pop();

        while(!q.empty())
            nums.insert(nums.begin(), q.front()), q.pop();
        return;
    }
};

/// Cyclic Replacements
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class SolutonB{
public: 
    void rotate(vector<int>& nums, int k){
        int start = 0, cur = 0, t = nums[cur];
        for(int i=0; i<nums.size(); i++){
            int next = (cur + k) % nums.size();
            int t2 = nums[next];
            nums[next] = t;
            t = t2;
            cur = next;

            if(cur == start)
                start++, cur=start, t=nums[cur];
        }
    }
};

/// Using Reverse
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class SolutionC {
public:
    void rotate(vector<int>& nums, int k) {

        k %= nums.size();
        reverse(nums, 0, nums.size() - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.size() - 1);
    }

private:
    void reverse(vector<int>& nums, int start, int end){
        for(int i = start, j = end; i < j; i ++, j --)
            swap(nums[i], nums[j]);
    }
};

void print_vec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    vector<int> nums1 = {1, 2, 3, 4, 5, 6, 7};
    SolutionC().rotate(nums1, 3);
    print_vec(nums1);

    vector<int> nums2 = {1, 2};
    SolutionC().rotate(nums2, 3);
    print_vec(nums2);

    return 0;
}

楊輝三角 II

給定一個非負索引 k,其中 k ≤ 33,返回楊輝三角的第 k 行。

img

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 3
輸出: [1,3,3,1]

進階:

你可以優化你的算法到 O(k) 空間復雜度嗎?

#include <iostream>
#include <vector>

using namespace std;

/// Simulate Pascal Triangle
///
/// Time Complexity: O(rowIndex^2)
/// Space Complexity: O(rowIndex^2)
class SolutionA{
public: 
    vector<int> getRow(int rowIndex){
        vector<vector<int>> res(rowIndex+1, vector<int>(rowIndex+1, 1));
        for(int i=2; i<=rowIndex; i++)
            for(int j=1; j<i; j++)
                res[i][j] = res[i-1][j-1] + res[i-1][j];
        return res[rowIndex];
    }
};

/// Simulate Pascal Triangle
///
/// Time Complexity: O(rowIndex^2)
/// Space Complexity: O(rowIndex)
class SolutionB{
public: 
    vector<int> getRow(int rowIndex){
        vector<int> up(rowIndex+1, 1);
        vector<int> down(rowIndex+1, 1);
        for(int i=2; i<=rowIndex; i++){
            for(int j=1; j<i; j++)
                down[j] = up[j-1] + up[j];
            up = down;
        }
        return down;
    }
};

void print_vec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    print_vec(SolutionB().getRow(3));

    return 0;
}

翻轉字符串里的單詞

給定一個字符串,逐個翻轉字符串中的每個單詞。

示例 1:

輸入: "the sky is blue"
輸出: "blue is sky the"

示例 2:

輸入: "  hello world!  "
輸出: "world! hello"
解釋: 輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的·字符不能包括。

示例 3:

輸入: "a good   example"
輸出: "example good a"
解釋: 如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。

說明:

  • 無空格字符構成一個單詞。
  • 輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的字符不能包括。
  • 如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。

進階:

請選用 C 語言的用戶嘗試使用 O(1) 額外空間復雜度的原地解法。

#include <iostream>
#include <vector>

using namespace std;

/// Reverse then reverse:)
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution
{
public:
    string reverseWords(string s)
    {
        int start = nextNonSpace(s, 0);
        s = s.substr(start);

        start = 0;
        for (int i = start + 1; i <= s.size();)
            if (i == s.size() || s[i] == ' ')
            {
                start = nextNonSpace(s, i);
                if (start != s.size())
                    s = s.substr(0, i) + " " + s.substr(start); //除去字符串中多余的空格。
                else
                {
                    s = s.substr(0, i);
                    break;
                }
                start = i + 1;
                i = start + 1;
            }
            else
                i++;
        reverse(s, 0, s.size() - 1);
        start = 0;
        for (int i = start + 1; i <= s.size();)
            if (i == s.size() || s[i] == ' ')
            {
                reverse(s, start, i - 1);
                start = i + 1;
                i = start + 1;
            }
            else
                i++;
        
        return s;
    }

private:
    int nextNonSpace(const string &s, int start)
    {
        int i = start;
        for (; i < s.size(); i++)
            if (s[i] != ' ')
                return i;
        return i;
    }
    void reverse(string &s, int start, int end)
    {
        int i = start, j = end;
        while (i < j)
            swap(s[i++], s[j--]);
    }
};
int main() {

    string s1 = "the sky is blue";
    Solution().reverseWords(s1);
    cout << s1 << endl;

    string s2 = "";
    Solution().reverseWords(s2);
    cout << s2 << endl;

    string s3 = " 1 ";
    Solution().reverseWords(s3);
    cout << s3 << endl;

    string s4 = "   a   b ";
    Solution().reverseWords(s4);
    cout << s4 << endl;

    return 0;
}

反轉字符串中的單詞 III

給定一個字符串,你需要反轉字符串中每個單詞的字符順序,同時仍保留空格和單詞的初始順序。

示例 1:

輸入: "Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每個單詞由單個空格分隔,並且字符串中不會有任何額外的空格。

#include <iostream>

using namespace std;

/// Reverse in place
/// Time Complexity: O(len(s))
/// Space Complexity: O(1)
class Solution{
public: 
    string reverseWords(string s){
        int start = 0;
        for(int i=start + 1; i<=s.size(); )
            if(i == s.size() || s[i] == ' '){   //空格翻轉無影響
                reverse(s, start, i-1);
                start = i+1;
                i = start + 1;
            }
            else 
                i ++;
        return s;
    }
private: 
    void reverse(string& s, int start, int end){
        for(int i = start, j = end; i<j; )
            swap(s[i++], s[j--]);
    }
};

刪除排序數組中的重復項

給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素只出現一次,返回移除后數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。

示例 1:

給定數組 nums = [1,1,2], 

函數應該返回新的長度 2, 並且原數組 nums 的前兩個元素被修改為 1, 2。 

你不需要考慮數組中超出新長度后面的元素。

示例 2:

給定 nums = [0,0,1,1,1,2,2,3,3,4],

函數應該返回新的長度 5, 並且原數組 nums 的前五個元素被修改為 0, 1, 2, 3, 4。

你不需要考慮數組中超出新長度后面的元素。

說明:

為什么返回數值是整數,但輸出的答案是數組呢?

請注意,輸入數組是以“引用”方式傳遞的,這意味着在函數里修改輸入數組對於調用者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);

// 在函數里修改輸入數組對於調用者是可見的。
// 根據你的函數返回的長度, 它會打印出數組中該長度范圍內的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>

using namespace std;

/// Two pointers
/// Time Complexity:  O(n)
/// Space Complexity: O(1)
class Solution{
public: 
    int removeDuplicates(vector<int>& nums){
        if(nums.size()==0)
            return 0;
        
        int res = 1;
        int index = nextDifferentCharacterIndex(nums, 1);
        int i = 1;
        while(index < nums.size()){
            res++;
            nums[i++] = nums[index];
            index = nextDifferentCharacterIndex(nums, index + 1);
        }
        return res;
    }
private: 
    int nextDifferentCharacterIndex(const vector<int> & nums, int p){
        for(; p<nums.size(); p++)
            if(nums[p] != nums[p-1])
                break;
        return p;
    }
};

int main(){
    vector<int> nums1 = {1, 1, 2};
    cout << Solution().removeDuplicates(nums1) << endl;

    return 0;
}

移動零

給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。

示例:

輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]

說明:

  1. 必須在原數組上操作,不能拷貝額外的數組。
  2. 盡量減少操作次數。
#include <iostream>
#include <vector>

using namespace std;

// Time Complexity: O(n)
// Space Complexity: O(n)
class Solution{
public: 
    void moveZeroes(vector<int>& nums){
        vector<int> nonZeroElements;

        // put all the non zero elements into a new vector
        for(int i = 0; i<nums.size(); i++)
            if(nums[i])
                nonZeroElements.push_back(nums[i]);
        
        // make nums[0...nonZeroElements.size()) all non zero elements
        for(int i = 0; i<nonZeroElements.size(); i++)
            nums[i] = nonZeroElements[i];

        // make nums[nonZeroElements.size()...nums.size()) all zero elements
        for(int i = nonZeroElements.size(); i<nums.size(); i++)
            nums[i] = 0;
    };
};
void printVec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}
int main() {

    int arr[] = {0, 1, 0, 3, 12};
    vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
    Solution().moveZeroes(vec);
    printVec(vec);

    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM