Leetcode_Q1 two numbers (C ++)

And two numbers (C ++)

topic

Given an integer array nums and a target value target, and you find that the target value in the array of two integers, and return to their array subscript. You can assume that each input corresponds to only one answer. However, you can not re-use the same array element .

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/two-sum

A brute-force method

Thinking

Each of the two respectively adjacent numbers are added, it is equal to the target output of these two numbers of array subscript. Note that the number can not be reused, so two different conditions need to meet the numerical subscript. It should here be a loop statement and judgment .

time complexity

For each element, we are trying to find the target element to which it corresponds to the rest of iterate, which will cost O (n) O (n) time. Thus the time complexity is O (n- 2 ).

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i,j;
        for(i=0;i<nums.size()-1;i++)
            for(j=1;j<nums.size();j++)
                if(nums[i]+nums[j]==target&&i!=j)
                    return {i,j};  //vector的列表初始化方法,相当于返回一个包含值为i和j的vector
        return {i,j};
    }   
};

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> ans;
		for(int i = 0; i < nums.size(); ++ i){
			for(int j = i + 1; j < nums.size(); ++ j ){
				if(nums[i] + nums[j] == target){
					ans.push_back(i);
					ans.push_back(j);
		} } }
		return ans;
}
};
Tips:
  • Required length of the array: the array name .size ()
  • An array of length n index from 0 to n-1
  • The return value {0,1} are required, the direct return {i, j}
Thinking and problem
  • Leetcode brush in the first question, emm first pay attention to moderation, a title given conditions can not miss, otherwise there will be some test cases can not pass. For example, conditions of the problem without i ≠ j can not.
  • Input and output formats to adapt to the site, probably needs over time. .
  • Note the use of return statements. if a sentence in return, had to return back again to compile. Note that the return value format.

B hash table method

Ideas and complexity

  • Hash table is a data structure can be found according to the value of index value, i.e. the Map [value] = Key .
  • When a plurality of index values corresponding to the foregoing index is covered .
  • And common array Map [key] = value just the opposite. Hash table is one to one hash table, is generally considered to find complexity is o (1). Hash table is a space for time . Increase much space, but greatly reduces the time-consuming.
Two hash

First of all the index values ​​and fill into the hash table, and then to find out.

A hash

Eliminating the process of establishing all the elements of the hash table. In the element inserted into the table at the same time, check whether there is a target table element corresponding to the current element. If it exists, then we have found a solution corresponding to, and immediately returned.
Here Insert Picture Description

//两次哈希
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {//引用,nums会跟着操作而改变

        unordered_map<int,int> m;   //定义一个名为m的哈希表

        for(int i=0;i<nums.size();i++)
            m[nums[i]]=i;   //向map中添加nums中的所有元素
        
        for(int i=0;i<nums.size();i++)//还是两次遍历
        {
            if(m.find(target-nums[i])!=m.end()&&m[target-nums[i]]!=i)//m中存在对应键值,并且不为i
                return {i,m[target-nums[i]]};
        }
        return {};
    }
};

//一次哈希
class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
	unordered_map<int,int> m;
	for(int i = 0;i < nums.size(); ++ i){
		if(m.find(target-nums[i]) != m.end())//m 中存在对应的键值
			return {m[target-nums[i]],i};//因为 i 为较大的元素,此时添加进去的键值都还小于 i,所以 i 在后面
			m[nums[i]]=i; //没找到合适的键值,向 map 中添加元素
		}
	return {};
}
};

Extended C: binary search

The basic idea:

The n elements is divided into two approximately equal portions, to take a [n / 2] x and compared, if x = a [n / 2], x is found, abort algorithm; if x <a [n / 2] , as long as the left half of the array in a continued search for x, if x> a [n / 2], the search for the right half of x as long as the array a.

Algorithm requires:
  • It must sequential storage structure;
  • Keyword must be ordered by size.
Time complexity: the number of the while loop.

A total of n elements, with gradually down is n, n / 2, n / 4, ... n / 2 ^ times (next operation of the remaining number of elements), where k is the cycle k.

= log K 2 n-, (based on base 2, n for logarithmic), i.e., O (H) = O (log 2 n-).

Code:
public static int Method(int[] nums, int low, int high, int target)
        {
            while (low <= high)
            {
                int middle = (low + high) / 2;
                if (target == nums[middle])
                {
                    return middle;
                }
                else if (target > nums[middle])
                {
                    low = middle + 1;
                }
                else if (target < nums[middle])
                {
                    high = middle - 1;
                }
            }
            return -1;
        }

//若给的数组已经排好顺序,可以使用二分查找法
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i,j,temp;
        for(i=0;i<nums.size()-1;i++){
            if(nums[i]>target) break;
             temp = target - nums[i];
             j = Method(nums,0,nums.size(),temp);
            if(b!=-1) break;
        }   
        return {i,j};
    }   
};
Published 76 original articles · won praise 30 · views 5839

Guess you like

Origin blog.csdn.net/weixin_45926367/article/details/104754637