LeetCode的medium题集合(C++实现)十二

1 Sqrt(x)

Implement int sqrt(int x).Compute and return the square root of x.

因为这里都是整数,可以直接采用二分法求解

int mySqrt(int x) {
       if (x <= 1) return x;
    int begin = 1, end =x, mid = 0;
    while (begin<=end)
    {
        mid = (begin + end) / 2;
        if (mid<x / mid) //不要用乘法判断,否则会越界
        {
            begin = mid + 1;
        }
        else if (mid>x / mid)
        {
            end = mid - 1;
        }
        else if (mid == x / mid)
            return mid;
    }
    return end;
    }

牛顿迭代法:设r是f(x)=0的根,选取x0作为r的初始近似值,过点(x0,f(x0))做曲线f(x)=y的切线L,L的方程为y=f′(x0)(x?x0)+f(x0),求出L与x轴交点的横坐标x1=x0?f(x0)f′(x0),称x1为r的一次近似值。过点(x1,f(x1))做曲线的切线,并求该切线与x轴交点的横坐标,称为r的二次近似值。重复以上过程,得r的近似值序列xn+1=xn?f(xn)f′(xn),其中,称为r的n+1次近似值,上式称为牛顿迭代公式。

当第n+1次与第n次近似值的差相差几乎为0时,即得到方程的解。

这里记f(x)=x2?X,求导得f′(x)=2x,代入上述迭代公式得到xn+1=xn/2+X/(2xn)

int mySqrt(int x) {
       if (x == 0)
        return 0;
    double last;
    double res = 1;
    do
    {
        last = res;
        res = x / (2 * last) + last / 2.0;
    } while (abs(res - last) > 0.001);
    return int(res);
    }

2 Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

用一个vector容器保存目录,当有多个’/’出现时去掉重复的,当出现’..’时是返回上一个目录,如果容器大小不为0,要去掉容器末尾的元素。

string simplifyPath(string path) {
        vector<string> res;
        int len=path.length();
        string mid;
        int start=0;
        while(start<len)
        {
            while(path[start]==‘/‘&&start<len)
                start++;  //去掉重复‘/‘
            while(path[start]!=‘/‘&&start<len)
            {
               //记录下每一级目录
                mid+=path[start];
                start++;
            }
            if(mid=="."||mid=="")
            {
                mid.clear(); //进入下一次循环前,记得清空mid
                continue;
            }
            if(mid=="..")
            {
                if(res.size()>0)
                   res.pop_back();
                mid.clear();
                continue;
            }
            res.push_back(mid);
            mid.clear();
        }
        string result;
        int n=res.size();
        for(int i=0;i<n;i++)
        {
            result=result+"/"+res[i];
        }
        if(result=="") result="/";
        return result;
    }
时间: 2024-10-10 18:09:09

LeetCode的medium题集合(C++实现)十二的相关文章

LeetCode的medium题集合(C++实现)十五

1 Subsets Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,3], a solution is: [ [3], [1],

LeetCode的medium题集合(C++实现)十

1 Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations.Given n and k, return the kth permutation sequence. 使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制.下面采用数学法: 在n!个排列中,第一位元素相同的排列总是有(n?1)!个,如果p=k/(n?1)!,那么排列的第一位元素

LeetCode的medium题集合(C++实现)十四

1 Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red,

LeetCode的medium题集合(C++实现)十六

1 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

LeetCode的medium题集合(C++实现)十一

1 Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked

LeetCode的medium题集合(C++实现)五

1 Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. 可以采用递归的方法解决这个问题,当找到一组数之和

LeetCode的medium题集合(C++实现)六

1 Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative. 该题实际就是利用字符串来解决大数的乘法问题.为了计算方便先将两组数翻转,将字符串转化为整数利用两个循环逐位相乘,将结果保存.然后逐位解决进位问题. s

LeetCode的medium题集合(C++实现)四

1 Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending or

LeetCode的medium题集合(C++实现)九

1 Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index. 利用两指针法