mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -246,11 +246,11 @@ var generateMatrix = function(n) {
|
||||
res[row][col] = count++;
|
||||
}
|
||||
// 下行从右到左(左闭右开)
|
||||
for (; col > startX; col--) {
|
||||
for (; col > startY; col--) {
|
||||
res[row][col] = count++;
|
||||
}
|
||||
// 左列做下到上(左闭右开)
|
||||
for (; row > startY; row--) {
|
||||
for (; row > startX; row--) {
|
||||
res[row][col] = count++;
|
||||
}
|
||||
|
||||
|
@ -364,7 +364,50 @@ var canCompleteCircuit = function(gas, cost) {
|
||||
};
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
**暴力法:**
|
||||
|
||||
```typescript
|
||||
function canCompleteCircuit(gas: number[], cost: number[]): number {
|
||||
for (let i = 0, length = gas.length; i < length; i++) {
|
||||
let curSum: number = 0;
|
||||
let index: number = i;
|
||||
while (curSum >= 0 && index < i + length) {
|
||||
let tempIndex: number = index % length;
|
||||
curSum += gas[tempIndex] - cost[tempIndex];
|
||||
index++;
|
||||
}
|
||||
if (index === i + length && curSum >= 0) return i;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
```
|
||||
|
||||
**解法二:**
|
||||
|
||||
```typescript
|
||||
function canCompleteCircuit(gas: number[], cost: number[]): number {
|
||||
let total: number = 0;
|
||||
let curGas: number = 0;
|
||||
let tempDiff: number = 0;
|
||||
let resIndex: number = 0;
|
||||
for (let i = 0, length = gas.length; i < length; i++) {
|
||||
tempDiff = gas[i] - cost[i];
|
||||
total += tempDiff;
|
||||
curGas += tempDiff;
|
||||
if (curGas < 0) {
|
||||
resIndex = i + 1;
|
||||
curGas = 0;
|
||||
}
|
||||
}
|
||||
if (total < 0) return -1;
|
||||
return resIndex;
|
||||
};
|
||||
```
|
||||
|
||||
### C
|
||||
|
||||
```c
|
||||
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
|
||||
int curSum = 0;
|
||||
|
@ -211,5 +211,29 @@ var largestSumAfterKNegations = function(nums, k) {
|
||||
};
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
function largestSumAfterKNegations(nums: number[], k: number): number {
|
||||
nums.sort((a, b) => Math.abs(b) - Math.abs(a));
|
||||
let curIndex: number = 0;
|
||||
const length = nums.length;
|
||||
while (curIndex < length && k > 0) {
|
||||
if (nums[curIndex] < 0) {
|
||||
nums[curIndex] *= -1;
|
||||
k--;
|
||||
}
|
||||
curIndex++;
|
||||
}
|
||||
while (k > 0) {
|
||||
nums[length - 1] *= -1;
|
||||
k--;
|
||||
}
|
||||
return nums.reduce((pre, cur) => pre + cur, 0);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user