2017.10.22 LeetCode

来源:互联网 发布:联通免费发短信软件 编辑:程序博客网 时间:2024/06/15 21:01

35. Search Insert Position

Description

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
题意 : 给你一个数组,和你个值,让你判断下如果这个值插入到数组里的话应该所在的下标

分析: 直接暴力即可

参考函数

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int ans = 0;        for(int i = 0;i < nums.size();i++) {            if(target > nums[i]) {                ans ++;            }            else {                return ans;            }        }        return ans;    }};

66. Plus One

Description

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

题意: 让你一个数组这个数组里面有不少数,但都是个位数,是对一个整数按位取出来后放进去的,然后让你在原有表示整数的基础上加上1,然后存到数组里

分析 : 题意一开始不怎么理解,后来试了几次后知道了,比如一开始 digits里面有两个元素分别为[1,2],就是代表12这个数,然后我们返回时数组里应该是[1,3]这样,我们只需要考虑下如果有进位的情况,尤其是再多进一位,比如[9] ->[1,0] 这样的,看函数吧,一看便知

参考函数

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        for(int i = digits.size() - 1;i >= 0;i --) {            if(digits[i] == 9) {                digits[i] = 0;            }else {                digits[i]++;                return digits;            }        }        digits[0] = 1;        digits.push_back(0);//这里很巧妙        return digits;    }};