Array

414. Third Maximum Number

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        long int first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == first || nums[i] == second || nums[i] == third) continue;
            if (nums[i] > first) {
                third = second;
                second = first;
                first = nums[i];
            }
            else if (nums[i] > second) {
                third = second;
                second = nums[i];
            }
            else if (nums[i] > third) {
                third = nums[i];
            }
        }
        return third == LONG_MIN?first:third;
    }
};

88. Merge Sorted Array

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        if (m == 0) nums1 = nums2;
        int idx = m + n - 1;
        while (m > 0 && n > 0) {
            if (nums2[n-1] < nums1[m-1]) {
                nums1[idx] = nums1[m-1];
                m--;
            }
            else {
                nums1[idx] = nums2[n-1];
                n--;
            }
            idx--;
        }
        while (n > 0) {
            nums1[idx] = nums2[n-1];
            n--;
            idx--;
        } 
    }
};

27. Remove Element

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        int i = 0;
        int j = 0;
        for (i = 0; i < size; ++i) {
            if (nums[i] == val) continue;
            nums[j] = nums[i];
            j++;
        }
        return j;
    }
};











					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s