zoukankan      html  css  js  c++  java
  • Leetcode 题目整理 Sqrt && Search Insert Position

    Sqrt(x)

    Implement int sqrt(int x).

    Compute and return the square root of x.

    注:这里的输入输出都是整数说明不会出现 sqrt(7)这种情况,思路一就是应用二分法进行查找。每次给出中间值,然后比对cur的平方与目标值的大小。需要先设定两个变量用来存放左右游标。

    这里要考虑一下整型溢出的问题,另外,即使不能开出整数的也要近似给出整数部分,不能忽略。

    代码如下:

    int Solution::mySqrt(int x) {
    	//输入一个整数,输出它的平方根
    	if (x == 1)
    		return x;
    
    	long long int s;
    	s = x / 2;
    	long long int leftflag = 0, rightflag = x;
    	while (s*s != x && leftflag+1<rightflag)
    	{
    
    		if (s*s < x)
    		{//在右侧区间内寻找
    			leftflag = s;
    		}
    		else
    		{
    			rightflag = s;
    		}
    		s = (leftflag + rightflag) / 2;
    		cout << "left " << leftflag << endl;
    		cout << "right" << rightflag << endl;
    		cout << "s" << s << endl;
    	} 
    		return s;
    
    	/*来自博客的一个参考,更简练一些*/
    		//long long left = 0, right = (x / 2) + 1;
    		//while (left <= right) {
    		//	long long mid = (left + right) / 2;
    		//	long long sq = mid * mid;
    		//	if (sq == x) return mid;
    		//	else if (sq < x) left = mid + 1;
    		//	else right = mid - 1;
    		//}
    		//return right;
    
    }
    

    Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    You may assume no duplicates in the array.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    注:给出一个矩阵(有序的)和目标值,找到目标值所在位置(如果有),或者应该插入的位置(如果没有)。

    思路:从左向右进行遍历,发现第一个不小于目标值的元素时,对位置进行记录。

    代码如下:

    int Solution::searchInsert(vector<int>& nums, int target) {
    	int position=0;
    	vector<int>::iterator iter = nums.begin();
    	while (iter != nums.end() && target > *iter)// && target != *iter)
    	{
    		iter++; position++;
    	}
    
    	return position;
    }
    
  • 相关阅读:
    第五篇:在SOUI中使用XML布局属性指引(pos, offset, pos2type)
    第四篇:SOUI资源文件组织
    第三篇:用SOUI能做什么?
    第二篇:SOUI源码的获取及编译
    第一篇:SOUI是什么?
    BuildFilePath 及打开文件对话框
    Java的synchronized关键字:同步机制总结
    Synchronized Methods
    java synchronized详解
    深拷贝与浅拷贝探析
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6757470.html
Copyright © 2011-2022 走看看