classSolution{public:
vector<string>summaryRanges(vector<int>& nums){
vector<string> res;for(int i =0; i < nums.size(); i ++){int j = i +1;while(j < nums.size()&& nums[j]== nums[j -1]+1) j ++;if(j == i +1) res.push_back(to_string(nums[i]));else res.push_back(to_string(nums[i])+"->"+to_string(nums[j -1]));
i = j -1;}return res;}};
classSolution{public List<String>summaryRanges(int[] nums){
List<String> ret =newArrayList<String>();int i =0;int n = nums.length;while(i < n){int low = i;
i++;while(i < n && nums[i]== nums[i -1]+1){
i++;}int high = i -1;
StringBuffer temp =newStringBuffer(Integer.toString(nums[low]));if(low < high){
temp.append("->");
temp.append(Integer.toString(nums[high]));}
ret.add(temp.toString());}return ret;}}
classSolution:defsummaryRanges(self, nums: List[int])-> List[str]:
n =0
res =[]while n <len(nums):if n+1<len(nums)and nums[n]+1== nums[n+1]:
m = n
while n+1<len(nums)and nums[n]+1== nums[n+1]:
n +=1
res.append("{}->{}".format(nums[m],nums[n]))else:
res.append(str(nums[n]))
n +=1return res
funcsummaryRanges(nums []int)(ans []string){for i, n :=0,len(nums); i < n;{
left := i
for i++; i < n && nums[i-1]+1== nums[i]; i++{}
s := strconv.Itoa(nums[left])if left < i-1{
s +="->"+ strconv.Itoa(nums[i-1])}
ans =append(ans, s)}return}
classSolution:defkthSmallest(self, root, k):"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack =[]whileTrue:while root:
stack.append(root)
root = root.left
root = stack.pop()
k -=1ifnot k:return root.val
root = root.right
var ans intfunckthSmallest(root *TreeNode, k int)int{dfs(root,&k)return ans
}funcdfs(root *TreeNode, k *int){if root !=nil{dfs(root.Left, k)*k--if*k ==0{
ans = root.Val
}dfs(root.Right, k)}}
第二百三十一题:
classSolution{public:boolisPowerOfTwo(int n){return n >0&&(n &-n)== n;}};
classSolution{publicbooleanisPowerOfTwo(int n){if(n ==0)returnfalse;long x =(long) n;return(x &(x -1))==0;}}
classSolution(object):defisPowerOfTwo(self, n):if n ==0:returnFalsereturn n &(n -1)==0
//gofuncisPowerOfTwo(n int)bool{return n >0&& n&(n-1)==0}
第二百三十二题:
classMyQueue{public:/** Initialize your data structure here. */
stack<int> a, b;MyQueue(){}/** Push element x to the back of queue. */voidpush(int x){
a.push(x);}/** Removes the element from in front of queue and returns that element. */intpop(){while(a.size()>1) b.push(a.top()), a.pop();int t = a.top();
a.pop();while(b.size()) a.push(b.top()), b.pop();return t;}/** Get the front element. */intpeek(){while(a.size()>1) b.push(a.top()), a.pop();int t = a.top();while(b.size()) a.push(b.top()), b.pop();return t;}/** Returns whether the queue is empty. */boolempty(){return a.empty();}};/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
classMyQueue{private Stack<Integer> inStack;private Stack<Integer> outStack;/** Initialize your data structure here. */publicMyQueue(){
inStack =newStack<>();
outStack =newStack<>();}/** Push element x to the back of queue. */publicvoidpush(int x){
inStack.push(x);}privatevoidtransfer(){while(!inStack.isEmpty()){
outStack.push(inStack.pop());}}/** Removes the element from in front of queue and returns that element. */publicintpop(){if(outStack.isEmpty()){transfer();}return outStack.pop();}/** Get the front element. */publicintpeek(){if(outStack.isEmpty()){transfer();}return outStack.peek();}/** Returns whether the queue is empty. */publicbooleanempty(){return inStack.isEmpty()&& outStack.isEmpty();}}
classMyQueue:def__init__(self):"""
Initialize your data structure here.
"""
self.stack1 =[]# 主栈
self.stack2 =[]# 辅助栈defpush(self, x:int)->None:"""
Push element x to the back of queue.
"""
self.stack1.append(x)defpop(self)->int:"""
Removes the element from in front of queue and returns that element.
"""whilelen(self.stack1)>1:
self.stack2.append(self.stack1.pop())
element = self.stack1.pop()whilelen(self.stack2)>0:
self.stack1.append(self.stack2.pop())return element
defpeek(self)->int:"""
Get the front element.
"""whilelen(self.stack1)>1:
self.stack2.append(self.stack1.pop())
element = self.stack1.pop()
self.stack2.append(element)whilelen(self.stack2)>0:
self.stack1.append(self.stack2.pop())return element
defempty(self)->bool:"""
Returns whether the queue is empty.
"""returnlen(self.stack1)==0# Your MyQueue object will be instantiated and called as such:# obj = MyQueue()# obj.push(x)# param_2 = obj.pop()# param_3 = obj.peek()# param_4 = obj.empty()
type MyQueue struct{
Input *stackArr
Output *stackArr
}/** Initialize your data structure here. */funcConstructor() MyQueue {return MyQueue{
Input:&stackArr{
Element:make([]int,0),
size:0,},
Output:&stackArr{
Element:make([]int,0),
size:0,},}}/** Push element x to the back of queue. */func(this *MyQueue)Push(x int){
this.Input.Push(x)}/** Removes the element from in front of queue and returns that element. */func(this *MyQueue)Pop()int{if this.Output.Empty(){for!this.Input.Empty(){
this.Output.Push(this.Input.Pop())}}return this.Output.Pop()}/** Get the front element. */func(this *MyQueue)Peek()int{if this.Output.Empty(){for!this.Input.Empty(){
this.Output.Push(this.Input.Pop())}}return this.Output.Top()}/** Returns whether the queue is empty. */func(this *MyQueue)Empty()bool{return this.Input.Empty()&& this.Output.Empty()}type stackArr struct{
Element []int
size int}func(s *stackArr)Empty()bool{return s.size ==0}func(s *stackArr) Pop ()int{var result intif!s.Empty(){
maxKey := s.size -1
result = s.Element[maxKey]
s.Element = s.Element[:maxKey]
s.size--}return result
}func(s *stackArr)Push(x int){if s.Element !=nil{
s.Element =append(s.Element, x)
s.size++}}func(s *stackArr) Top ()int{if s.Empty(){return0}return s.Element[s.size-1]}/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/
第二百三十三题:
classSolution{public:intcountDigitOne(int n){if(n <=0)return0;
vector<int> nums;while(n) nums.push_back(n %10), n /=10;reverse(nums.begin(), nums.end());int res =0;for(int i =0; i < nums.size(); i ++){int d = nums[i];int left =0, right =0, p =1;for(int j =0; j < i; j ++) left = left *10+ nums[j];for(int j = i +1; j < nums.size(); j ++){
right = right *10+ nums[j];
p = p *10;}if(d ==0) res += left * p;elseif(d ==1) res += left * p + right +1;else res +=(left +1)* p;}return res;}};
classSolution{publicintcountDigitOne(int n){if(n<1)return0;int[] f =newint[10];
f[0]=1;for(int i=1;i<f.length;i++)f[i]= f[i-1]*10;int ans =0;
String s = String.valueOf(n+"");for(int i=0;i<s.length();i++){for(int j=0;j<i;j++){
ans +=(s.charAt(j)-'0')*f[s.length()-j-2];}if(s.charAt(i)>'1'){
ans += f[s.length()-i-1];}elseif(s.charAt(i)=='1'){if(i<s.length()-1)ans += Integer.parseInt(s.substring(i+1))+1;else ans++;}}return ans;}}
classSolution:defcountDigitOne(self, n:int)->int:
k =1
base =1
count =0if n<=0:return0while n//base !=0:
cur =(n//base)%10
high = n//(base*10)
low = n - n//base*base
if cur>k:
count +=(high+1)*base
if cur==k:
count += high*base+low+1if cur <k:
count += high*base
base*=10return count
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/classSolution{public:boolisPalindrome(ListNode* head){int n =0;for(auto p = head; p; p = p->next) n ++;if(n <=1)returntrue;int half = n /2;auto a = head;for(int i =0; i < n - half; i ++) a = a->next;auto b = a->next;for(int i =0; i < half -1; i ++){auto c = b->next;
b->next = a;
a = b, b = c;}auto p = head, q = a;bool success =true;for(int i =0; i < half; i ++){if(p->val != q->val){
success =false;break;}
p = p->next;
q = q->next;}auto tail = a;
b = a->next;// 将链表恢复原状for(int i =0; i < half -1; i ++){auto c = b->next;
b->next = a;
a = b, b = c;}
tail->next =NULL;return success;}};
classSolution:defisPalindrome(self, head: ListNode)->bool:if head isNone:returnTrue# 找到前半部分链表的尾节点并反转后半部分链表
first_half_end = self.end_of_first_half(head)
second_half_start = self.reverse_list(first_half_end.next)# 判断是否回文
result =True
first_position = head
second_position = second_half_start
while result and second_position isnotNone:if first_position.val != second_position.val:
result =False
first_position = first_position.next
second_position = second_position.next# 还原链表并返回结果
first_half_end.next= self.reverse_list(second_half_start)return result
defend_of_first_half(self, head):
fast = head
slow = head
while fast.nextisnotNoneand fast.next.nextisnotNone:
fast = fast.next.next
slow = slow.nextreturn slow
defreverse_list(self, head):
previous =None
current = head
while current isnotNone:
next_node = current.next
current.next= previous
previous = current
current = next_node
return previous
funcreverseList(head *ListNode)*ListNode {var prev, cur *ListNode =nil, head
for cur !=nil{
nextTmp := cur.Next
cur.Next = prev
prev = cur
cur = nextTmp
}return prev
}funcendOfFirstHalf(head *ListNode)*ListNode {
fast := head
slow := head
for fast.Next !=nil&& fast.Next.Next !=nil{
fast = fast.Next.Next
slow = slow.Next
}return slow
}funcisPalindrome(head *ListNode)bool{if head ==nil{returntrue}// 找到前半部分链表的尾节点并反转后半部分链表
firstHalfEnd :=endOfFirstHalf(head)
secondHalfStart :=reverseList(firstHalfEnd.Next)// 判断是否回文
p1 := head
p2 := secondHalfStart
result :=truefor result && p2 !=nil{if p1.Val != p2.Val {
result =false}
p1 = p1.Next
p2 = p2.Next
}// 还原链表并返回结果
firstHalfEnd.Next =reverseList(secondHalfStart)return result
}
第二百二十八题:class Solution {public: vector<string> summaryRanges(vector<int>& nums) { vector<string> res; for (int i = 0; i < nums.size(); i ++ ) { int j = i + 1; while (j < nums.size()