LeetCode|【双指针】

来源:互联网 发布:淘宝网折800女士皮草 编辑:程序博客网 时间:2024/05/04 14:32

Move Zeroes

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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

class Solution {public:    void moveZeroes(vector<int>& nums) {        for(int lastNon = 0, i = 0; i < nums.size(); i++){            if(nums[i]){swap(nums[lastNon++], nums[i]);}        } return;    }};

Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

Hint:

  1. Try two pointers.
  2. Did you use the property of “the order of elements
  3. What happens when the elements to remove are rare?
方法一:class Solution {public:    int removeElement(vector<int>& nums, int val) {        int pos = 0;        for(int i = 0; i < nums.size(); i++){            if(nums[i] != val){                nums[pos++] = nums[i];            }        } return pos;    }};

方法二:
p1指针从前往后,p2指针从后往前.(cont.)

Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

class Solution {public:    string reverseVowels(string s) {        int l = 0, r = s.length()-1;        while(l < r){            while( !isVowel(s[l]) && l < r){l++;}            while( !isVowel(s[r]) && l < r){r--;}            if(l < r) {swap(s[l++], s[r--]);} // ++, -- after swap        } return s;    }    private:    bool isVowel(char c){        switch(c){            case 'a':            case 'A':            case 'e':            case 'E':            case 'i':            case 'I':            case 'o':            case 'O':            case 'u':            case 'U':            return true;            default:;        }        return false;    }};

Remove Duplicates from Sorted Array

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.

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() == 0) return 0;        int pos = 0, theLast = nums.size()-1;        for(int i = 0; i < theLast; i++){            if(nums[i] != nums[i+1]){                nums[pos++] = nums[i];            }         } nums[pos++] = nums[theLast];         return pos;    }};

Remove Duplicates from Sorted Array II

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() < 3) return nums.size(); // at least 3 elements        int n = nums.size(), pos = 0, cnt = 1;        for(int i = 1; i < n; i++){            if(nums[pos] != nums[i]){                nums[++pos] = nums[i];                cnt = 1;            }            else if(++cnt < 3) nums[++pos] = nums[i];        } return pos+1;    }};

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head == NULL) return NULL;        ListNode fakeHead(-1), *p = &fakeHead;        while(head->next){            if(head->val != head->next->val){                p->next = head;                p = p->next;            }             head = head->next;        } p->next = head;        return fakeHead.next;    }};

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {        if(head == NULL || head->next == NULL) return head;        ListNode fakeNode(-1);        ListNode *p1 = &fakeNode, *p2 = head;        int cnt = 1;        while(p2){            if(p2->next == NULL || p2->val != p2->next->val){                if(cnt == 1){                    p1->next = p2;                    p1 = p1->next;                } else cnt = 1;            } else cnt++;            p2 = p2->next;        } p1->next = NULL;        return fakeNode.next;    }};

心得:结尾NULL

Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

class Solution {public:    bool isPalindrome(string str) {        if(str.empty()  || str.size() == 1) return true; // all the chars are not  alphanumeric is also true        int s = 0, e = str.size()-1;        while(s < e){            while(!validChar(str[s]) && s < e){s++;}            while(!validChar(str[e]) && s < e){e--;}            if(s < e && str[s] != str[e]){                return false;            } else{                s++;                e--;            }        } return true;    }    private:    bool validChar(char& c){        if('A' <= c && c <= 'Z'){            c = c-'A' + 'a';            return true;        } else if (('a' <= c && c <= 'z' ) || ('0' <= c && c <= '9' ) ) {return true;}        return false;    }};

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

class Solution {public:    void rotate(vector<int>& nums, int k) {        k %= nums.size();        rotateBetween(nums, 0, nums.size()-k-1);        rotateBetween(nums, nums.size()-k, nums.size()-1);        rotateBetween(nums, 0, nums.size()-1);    }private:    void rotateBetween(vector<int>& nums, int l, int r){        while(l < r){            swap(nums[l++], nums[r--]);        }    }};
0 0
原创粉丝点击