LeetCode #14 (#167、#168、#169)

167. Two Sum II - Input array is sorted

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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
//Solution


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
//不会真的有人还看不懂吧?
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
    int i=0,j=numbersSize-1;
	while(i<=j)
    {
        if(numbers[i]+numbers[j]>target)
            j--;
        else if(numbers[i]+numbers[j]<target)
            i++;
        else 
        {
            *returnSize = 2;
			int *indexes = malloc(*returnSize * sizeof(int));
		    indexes[0] = i + 1;
		    indexes[1] = j + 1;
		    return indexes;
        }
    }
	*returnSize = 0;
    return NULL;
}

168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

   1 -> A
   2 -> B
   3 -> C
   ...
   26 -> Z
   27 -> AA
   28 -> AB 
   ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"
//Solution
class Solution {
public:
    string convertToTitle(int n) {
        string out;
        while(n)
        {       
            char c = (n-1)%26+'A';
            out.insert(out.begin(),c);
            n = (n-1)/26;
        }
        return out;
    }
};
169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
//Solution
int majorityElement(int* nums, int numsSize){
    int i = 0;
    int res = 0;
    int count = 0;
    for (;i < numsSize; ++i) {
        if (count == 0 || res == nums[i]) {
            res = nums[i];
            count++;
        } else {
            count--;
        }
    } 
    return res;
}

发布了74 篇原创文章 · 获赞 11 · 访问量 5987

猜你喜欢

转载自blog.csdn.net/weixin_44198992/article/details/105536042