206.反转链表
class Solution {
public ListNode reverseList ( ListNode head) {
ListNode cur, pre;
cur = head;
pre = null;
while ( cur!= null) {
ListNode nex = cur. next;
cur. next = pre;
pre = cur;
cur = nex;
}
return pre;
}
}
83.删除有序链表中的重复元素
struct ListNode * deleteDuplicates ( struct ListNode * head) {
struct ListNode * p= head;
while ( p&& p-> next) {
struct ListNode * q = p-> next;
while ( q&& q-> val== p-> val) {
q= q-> next;
}
p-> next= q;
p= p-> next;
}
return head;
}
53.最大子数组和
int maxSubArray ( int * nums, int numsSize) {
if ( numsSize == 1 )
return nums[ 0 ] ;
int i, this= 0 , a= 0 , max= - 10001 ;
for ( i= 0 ; i< numsSize; i++ ) {
this += nums[ i] ;
if ( max < this)
max = this;
if ( this <= 0 )
this = 0 ;
}
return max;
}
217.存在重复元素
class Solution {
public:
bool containsDuplicate ( vector< int > & nums) {
unordered_set< int > has;
for ( int i= 0 ; i< nums. size ( ) ; i++ ) {
if ( has. find ( nums[ i] ) != has. end ( ) )
return true;
has. insert ( nums[ i] ) ;
}
return false;
}
} ;
121.买股票的最佳时机
class Solution {
public int maxProfit ( int [ ] prices) {
int ans = - 10001 , minpro = prices[ 0 ] ;
for ( int i= 0 ; i< prices. length; i++ ) {
ans = Math. max ( ans, prices[ i] - minpro) ;
minpro = Math. min ( prices[ i] , minpro) ;
}
return ans> 0 ? ans: 0 ;
}
}
350.两个数组的交集
class Solution {
public :
bool beIn ( vector< int > & nums, int n, int l, int r) {
while ( l <= r) {
int mid = ( l+ r) / 2 ;
if ( nums[ mid] > n)
r = mid- 1 ;
else if ( nums[ mid] < n)
l = mid+ 1 ;
else {
nums. erase ( begin ( nums) + mid) ;
return true ;
}
}
return false ;
}
vector< int > intersect ( vector< int > & nums1, vector< int > & nums2) {
if ( nums1. empty ( ) )
return nums2;
if ( nums2. empty ( ) )
return nums1;
vector< int > ans;
if ( nums1. size ( ) < nums2. size ( ) ) {
sort ( nums2. begin ( ) , nums2. end ( ) ) ;
for ( int i : nums1) {
if ( beIn ( nums2, i, 0 , nums2. size ( ) - 1 ) ) {
ans. push_back ( i) ;
}
}
} else {
sort ( nums1. begin ( ) , nums1. end ( ) ) ;
for ( int i : nums2) {
if ( beIn ( nums1, i, 0 , nums1. size ( ) - 1 ) )
ans. push_back ( i) ;
}
}
return ans;
}
} ;
重塑矩阵
class Solution {
public :
vector< vector< int >> matrixReshape ( vector< vector< int >> & mat, int r, int c) {
if ( r* c == mat. size ( ) * mat[ 0 ] . size ( ) ) {
int row= 0 , col= 0 ;
int len_col = mat[ 0 ] . size ( ) ;
int len_row = mat. size ( ) ;
vector< vector< int >> ans;
for ( int i= 0 ; i< r; i++ ) {
vector< int > pos;
for ( int j= 0 ; j< c; j++ ) {
pos. push_back ( mat[ row] [ col++ ] ) ;
if ( col == len_col) {
row++ ;
col = 0 ;
}
}
ans. push_back ( pos) ;
}
return ans;
}
return mat;
}
} ;