1、连续子数组的最大和
1.1 题目描述:
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
时间复杂度为O(n)。
1.2 题解
1.2.1 动态规划
public int maxSubArray(int[] nums) {
int res=nums[0];
for(int i=1;i<nums.length;i++)
{
if(nums[i-1]>0)
nums[i]+=nums[i-1];
if(nums[i]>res)
res=nums[i];
}
return res;
}
2、1~n整数中1出现的次数
2.1 题目描述:
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
2.2 题解
2.2.1
将 11 ~ nn 的个位、十位、百位、…的 11 出现次数相加,即为 11 出现的总次数
public int countDigitOne(int n) {
int high=n/10,low=0;
int digit=1,cur=n%10;;
int res=0;
while(high!=0||cur!=0){
if(cur==0)res+=high*digit;
else if(cur==1)res+=high*digit+1+low;
else res += (high + 1) * digit;
low+=cur*digit;
cur=high%10;
high/=10;
digit*=10;
}
return res;
}
3、数字序列中某一位的数字
3.1 题目描述:
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字
3.2 题解
3.2.1
- 确定所求数位的所在数字的位数
2.确定所求数位所在的数字
- 确定所求数位在 numnum 的哪一数位
public int findNthDigit(int n) {
int digit = 1; //数字 10是一个两位数,称此数字的 位数 为 2 ,记为 digit
long start = 1;//每 digit 位数的起始数字(即:1, 10, 100),记为 start
long count = 9;//数位数量
while (n>count){//跳出时,已经找到了所在的数位中
n-=count;
digit++;
start*=10;
count=start*digit*9;
}
Long num=start+(n-1)/digit;//确定所求数位所在的数字
int res = Long.toString(num).charAt((n - 1) % digit) - '0';// 3.
return res;
}