剑指 Offer 45. 把数组排成最小的数
题目
思路
快排+特殊规则;
代码
class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0; i < nums.length; i++)
strs[i] = String.valueOf(nums[i]);
fastSort(strs, 0, strs.length - 1);
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
void fastSort(String[] strs, int l, int r) {
if(l >= r) return;
int i = l, j = r;
String tmp = strs[i];
while(i < j) {
while((strs[j] + strs[l]).compareTo(strs[l] + strs[j]) >= 0 && i < j) j--;
while((strs[i] + strs[l]).compareTo(strs[l] + strs[i]) <= 0 && i < j) i++;
tmp = strs[i];
strs[i] = strs[j];
strs[j] = tmp;
}
strs[i] = strs[l];
strs[l] = tmp;
fastSort(strs, l, i - 1);
fastSort(strs, i + 1, r);
}
}
class Solution:
def minNumber(self, nums: List[int]) -> str:
def fast_sort(l , r):
if l >= r: return
i, j = l, r
while i < j:
while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1
while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1
strs[i], strs[j] = strs[j], strs[i]
strs[i], strs[l] = strs[l], strs[i]
fast_sort(l, i - 1)
fast_sort(i + 1, r)
strs = [str(num) for num in nums]
fast_sort(0, len(strs) - 1)
return ''.join(strs)
剑指 Offer 46. 把数字翻译成字符串
题目
思路
代码
class Solution {
public int translateNum(int num) {
String str=String.valueOf(num);
int a=1,b=1;
for(int i=2;i<=str.length();i++){
String tmp=str.substring(i-2,i);
int c=tmp.compareTo("10")>=0&&tmp.compareTo("25")<=0?a+b:b;
a=b;
b=c;
}
return b;
}
}
class Solution:
def translateNum(self, num: int) -> int:
st=str(num)
a,b=1,1
for i in range(2,len(st)+1):
tmp=st[i-2:i]
if tmp>='10' and tmp<='25':
c=a+b
else:
c=b
a=b
b=c
return b