repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
smiley/ebpf-for-windows | libs/api/Verifier.h | <reponame>smiley/ebpf-for-windows
/*
* Copyright (c) Microsoft Corporation
* SPDX-License-Identifier: MIT
*/
#pragma once
#include "config.hpp"
#undef VOID
#include "platform.hpp"
#define VOID void
typedef int (*map_create_fp)(
uint32_t map_type, uint32_t key_size, uint32_t value_size, uint32_t max_entries, ebpf_verifier_options_t options);
int
get_file_size(const char* filename, size_t* byte_code_size);
int
load_byte_code(
const char* filename,
const char* sectionname,
uint8_t* byte_code,
size_t* byte_code_size,
ebpf_program_type_t* program_type);
int
verify_byte_code(
const char* path,
const char* section_name,
const uint8_t* byte_code,
size_t byte_code_size,
const char** error_message);
|
smiley/ebpf-for-windows | libs/platform/ebpf_program_types.c | /*
* Copyright (c) Microsoft Corporation
* SPDX-License-Identifier: MIT
*/
#include "ebpf_platform.h"
#include "ebpf_program_types_c.c"
ebpf_error_code_t
ebpf_program_information_encode(
const ebpf_program_information_t* program_information, uint8_t** buffer, unsigned long* buffer_size)
{
handle_t handle = NULL;
ebpf_program_information_pointer_t local_program_information = (ebpf_program_information_t*)program_information;
RPC_STATUS status = MesEncodeDynBufferHandleCreate((char**)buffer, buffer_size, &handle);
if (status != RPC_S_OK)
return EBPF_ERROR_OUT_OF_RESOURCES;
RpcTryExcept { ebpf_program_information_pointer_t_Encode(handle, &local_program_information); }
RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { status = RpcExceptionCode(); }
RpcEndExcept;
if (handle)
MesHandleFree(handle);
return status == RPC_S_OK ? EBPF_ERROR_SUCCESS : EBPF_ERROR_INVALID_PARAMETER;
}
ebpf_error_code_t
ebpf_program_information_decode(
ebpf_program_information_t** program_information, const uint8_t* buffer, unsigned long buffer_size)
{
handle_t handle = NULL;
ebpf_program_information_pointer_t local_program_information = NULL;
RPC_STATUS status = MesDecodeBufferHandleCreate((char*)buffer, buffer_size, &handle);
if (status != RPC_S_OK)
return EBPF_ERROR_OUT_OF_RESOURCES;
RpcTryExcept { ebpf_program_information_pointer_t_Decode(handle, &local_program_information); }
RpcExcept(RpcExceptionFilter(RpcExceptionCode())) { status = RpcExceptionCode(); }
RpcEndExcept;
if (handle)
MesHandleFree(handle);
if (status != RPC_S_OK)
return EBPF_ERROR_INVALID_PARAMETER;
*program_information = local_program_information;
return EBPF_ERROR_SUCCESS;
}
void* __RPC_USER
MIDL_user_allocate(size_t size)
{
return ebpf_allocate(size, EBPF_MEMORY_NO_EXECUTE);
}
void __RPC_USER
MIDL_user_free(void* p)
{
ebpf_free(p);
}
|
smiley/ebpf-for-windows | tests/end_to_end/helpers.h | /*
* Copyright (c) Microsoft Corporation
* SPDX-License-Identifier: MIT
*/
#pragma once
#include "ebpf_api.h"
#include "ebpf_link.h"
#include "ebpf_platform.h"
typedef class _single_instance_hook
{
public:
_single_instance_hook()
{
ebpf_guid_create(&attach_type);
REQUIRE(
ebpf_provider_load(
&provider,
&attach_type,
nullptr,
&provider_data,
nullptr,
this,
client_attach_callback,
client_detach_callback) == EBPF_ERROR_SUCCESS);
}
~_single_instance_hook() { ebpf_provider_unload(provider); }
uint32_t
attach(ebpf_handle_t program_handle)
{
return ebpf_api_link_program(program_handle, attach_type, &link_handle);
}
void
detach()
{
ebpf_api_close_handle(link_handle);
}
ebpf_error_code_t
fire(void* context, uint32_t* result)
{
ebpf_error_code_t (*invoke_program)(void* link, void* context, uint32_t* result) =
reinterpret_cast<decltype(invoke_program)>(client_dispatch_table->function[0]);
return invoke_program(client_binding_context, context, result);
}
private:
static ebpf_error_code_t
client_attach_callback(
void* context,
const GUID* client_id,
void* client_binding_context,
const ebpf_extension_data_t* client_data,
const ebpf_extension_dispatch_table_t* client_dispatch_table)
{
auto hook = reinterpret_cast<_single_instance_hook*>(context);
hook->client_id = *client_id;
hook->client_binding_context = client_binding_context;
hook->client_data = client_data;
hook->client_dispatch_table = client_dispatch_table;
return EBPF_ERROR_SUCCESS;
};
static ebpf_error_code_t
client_detach_callback(void* context, const GUID* client_id)
{
auto hook = reinterpret_cast<_single_instance_hook*>(context);
hook->client_binding_context = nullptr;
hook->client_data = nullptr;
hook->client_dispatch_table = nullptr;
UNREFERENCED_PARAMETER(client_id);
return EBPF_ERROR_SUCCESS;
};
ebpf_attach_type_t attach_type;
ebpf_extension_data_t provider_data = {0, 0};
ebpf_extension_provider_t* provider;
GUID client_id;
void* client_binding_context;
const ebpf_extension_data_t* client_data;
const ebpf_extension_dispatch_table_t* client_dispatch_table;
ebpf_handle_t link_handle;
} single_instance_hook_t;
typedef class _program_information_provider
{
public:
_program_information_provider(ebpf_program_type_t program_type) : program_type(program_type)
{
REQUIRE(
ebpf_provider_load(&provider, &program_type, nullptr, &provider_data, nullptr, nullptr, nullptr, nullptr) ==
EBPF_ERROR_SUCCESS);
}
~_program_information_provider() { ebpf_provider_unload(provider); }
private:
ebpf_program_type_t program_type;
ebpf_extension_data_t provider_data = {0, 0};
ebpf_extension_provider_t* provider;
} program_information_provider_t; |
kkarbowiak/cpp11-semaphore | semaphore.h | <gh_stars>0
/*
Copyright 2017 <NAME>
*/
#include <condition_variable>
#include <mutex>
namespace thr
{
template<typename C>
class semaphore
{
public:
semaphore();
explicit semaphore(C count);
void acquire();
void release();
private:
std::mutex mMutex;
std::condition_variable mCondVar;
C mCount;
};
}
namespace thr
{
////////////////////////////////////////////////////////////////////////////////
template<typename C>
inline semaphore<C>::semaphore()
: mMutex()
, mCondVar()
, mCount(0)
{
}
////////////////////////////////////////////////////////////////////////////////
template<typename C>
inline semaphore<C>::semaphore(C count)
: mMutex()
, mCondVar()
, mCount(count)
{
}
////////////////////////////////////////////////////////////////////////////////
template<typename C>
inline void semaphore<C>::acquire()
{
std::unique_lock<std::mutex> lock(mMutex);
while (mCount == 0)
{
mCondVar.wait(lock);
}
--mCount;
}
////////////////////////////////////////////////////////////////////////////////
template<typename C>
inline void semaphore<C>::release()
{
std::lock_guard<std::mutex> lock(mMutex);
++mCount;
mCondVar.notify_one();
}
////////////////////////////////////////////////////////////////////////////////
}
|
charliewilliams/CWNotificationBanner | Example/Pods/Target Support Files/Pods-CWNotificationBanner_Example/Pods-CWNotificationBanner_Example-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_CWNotificationBanner_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CWNotificationBanner_ExampleVersionString[];
|
charliewilliams/CWNotificationBanner | Example/Pods/Target Support Files/SwiftyTimer/SwiftyTimer-umbrella.h | <filename>Example/Pods/Target Support Files/SwiftyTimer/SwiftyTimer-umbrella.h
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double SwiftyTimerVersionNumber;
FOUNDATION_EXPORT const unsigned char SwiftyTimerVersionString[];
|
charliewilliams/CWNotificationBanner | Example/Pods/Target Support Files/CWNotificationBanner/CWNotificationBanner-umbrella.h | <reponame>charliewilliams/CWNotificationBanner<gh_stars>10-100
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double CWNotificationBannerVersionNumber;
FOUNDATION_EXPORT const unsigned char CWNotificationBannerVersionString[];
|
charliewilliams/CWNotificationBanner | Example/Pods/Target Support Files/Pods-CWNotificationBanner_Tests/Pods-CWNotificationBanner_Tests-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_CWNotificationBanner_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CWNotificationBanner_TestsVersionString[];
|
TemplateVoid/neoml | NeoMathEngine/src/CPU/x86/avx/src/BlobConvolution.h | /* Copyright © 2017-2020 ABBYY Production LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------------------------------------*/
#include <array>
#include <vector>
#include <algorithm>
#include <utility>
#include <NeoMathEngine/NeoMathEngine.h>
namespace NeoML {
class CBlobConvolutionBase : public CCrtAllocatedObject {
public:
virtual ~CBlobConvolutionBase() = default;
virtual void ProcessConvolution( int threadCount, const float* sourceData, const float* filterData, const float* freeTermData, float* resultData ) = 0;
};
template<int FltCnt>
class CBlobConvolution : public CBlobConvolutionBase {
public:
CBlobConvolution( IMathEngine* mathEngine,
int channelCount, int filterHeight, int filterWidth, int sourceHeight, int sourceWidth,
int paddingHeight, int paddingWidth, int strideHeight, int strideWidth,
int dilationHeight, int dilationWidth, int resultHeight, int resultWidth, int resObjCnt );
~CBlobConvolution() override = default;
void ProcessConvolution( int threadCount,
const float* sourceData, const float* filterData, const float* freeTermData, float* resultData ) override;
private:
struct CSize {
int Height;
int Width;
};
IMathEngine* mathEngine;
const int ChCnt;
const int FltH;
const int FltW;
const int SrcH;
const int SrcW;
const int PaddingH;
const int PaddingW;
const int StrideH;
const int StrideW;
const int DilationH;
const int DilationW;
const int ResH;
const int ResW;
const int ResObjCnt;
// For some cases we will use FltCnt, rounded up to nearest integer multiple of 8
static constexpr int FltCntM8 = ( FltCnt + 8 - 1 ) / 8 * 8;
static constexpr size_t AvxAlignment = 32;
const float* src;
const float* flt;
const float* freeTerm;
float* res;
// Length of one source line.
const int SrcLineStride;
// Distance in floats between two neighbor pixels in source.
const int SrcXStep;
const int SrcYStep;
// Distance in floats between two neighbor pixels in window by horizontal.
const int SrcXDilation;
// Distance in floats between two neighbor pixels in window by horizontal.
const int SrcYDilation;
// Width of source window in floats
const int SrcXWindowSize;
const int ResLineStride;
// When we move filter window over the source image we have different combination of intersection this window with
// source image. Filters window moves left to right and up to bottom, "PixelOffsetResStepsWidth..." - is number
// of steps which window moved till its intersection with source image changed.We will calculate steps over width and heigh.
std::vector<int> PixelOffsetResStepsWidthX;
std::vector<int> PixelOffsetResStepsWidthY;
// Choose proper pixels in source and filter:
// 0 1 2
// 3 4 5
// 6 7 8 (example for 3x3)
// Offset is relative to central pixel of source window
std::vector<std::vector<int>> SrcPixelsOffset;
// Offset is relative to center pixel of filter window
std::vector<std::vector<int>> FltPixelsOffset;
// In some cases when the width of the image is nearly equals to the width of optimized batch processing window,
// we may faced to situation ( when dilation is higth ) when no one optimized batch ptocessing can be
// applied. For such cases we will use optimized batch processing with narrower window but height greater then one.
const CSize NarrowBatchProcessSize;
const CSize WideBatchProcessSize;
// Initialize NarrowBatchProcessSize and WideBatchProcessSize
CSize getNarrowBatchProcessSize();
CSize getWideBatchProcessSize();
// Process one line of image. In case of narrow processing we will step through several lines.
void processConvolutionLoop( int rxSize, bool useNarrowProcessing, const float*& srcPtr, float*& resPtr, size_t windowIndex );
void batchProcessChannels( const float* srcPtr, const float* fltPtr,
__m256& r00, __m256& r01, __m256& r02,
__m256& r10, __m256& r11, __m256& r12,
__m256& r20, __m256& r21, __m256& r22 );
void batchProcessChannels( const float* srcPtr, const float* fltPtr,
__m256& r00, __m256& r01, __m256& r02, __m256& r03,
__m256& r10, __m256& r11, __m256& r12, __m256& r13 );
void batchProcessChannels( const float* srcPtr, const float* fltPtr, int srcNarrowStep,
__m256& r00, __m256& r01, __m256& r02,
__m256& r10, __m256& r11, __m256& r12,
__m256& r20, __m256& r21, __m256& r22 );
void singleProcessChannels( const float* srcPtr, const float* fltPtr, __m256& r0, __m256& r1, __m256& r2 );
void singleProcessChannels( const float* srcPtr, const float* fltPtr, __m256& r0, __m256& r1, __m256& r2, __m256& r3 );
void singleProcessChannels( const float* srcPtr, const float* fltPtr, __m256& r0 );
void singleProcessChannelsNarrow( const float* srcPtr, const float* fltPtr, __m256& r0, __m256& r1, __m256& r2 );
// Process convolution for multiple result pixels ( number of pixels is defined by 'FastBatchProcessSize' member ).
void batchProcess( const float* srcPtr, float* resPtr, size_t windowIndex, bool useNarrowProcessing );
// Process convolution for single result pixel.
void singleProcess( const float* srcPtr, float* resPtr, size_t windowIndex );
void singleProcessNarrow( const float* srcPtr, float* resPtr, size_t windowIndex );
// Rearrange filter and fill 'Filter' and 'FreeTerm' members.
const float* rearrangeFilter( const float* filterData, CFloatHandleStackVar& Filter );
const float* rearrangeFreeTerm( const float* freeTermData, CFloatHandleStackVar& FreeTerm );
// Function calculates offsets of center of filter window over the source image, where intersection over
// them is changed. This function helps to calculate further PixelOffsetResStepsWidthX/Y, SrcPixelsOffset and FltPixelsOffset.
// Src (source), F(filter), D(dilation), S(stride) and P(padding) linear dimention by X or Y axis.
std::vector<int> getPixelOffsetSrcSteps( int SrcDim, int FDim, int DDim, int SDim, int PDim );
// Initialize PixelOffsetResStepsX, PixelOffsetResStepsY, SrcPixelsOffset and FltPixelsOffset
void fillPixelOffset();
// Circular rotation of three ymm registers to the left, step equals to six floats.
static void rotateLeft6( __m256& y0, __m256& y1, __m256& y2 );
// Circular rotation of three ymm registers to the left, step equals to two floats.
static void rotateLeft2( __m256& y );
};
class CBlobConvolutionFabric : public CCrtAllocatedObject {
public:
static bool IsBlobConvolutionAvailable( int FltCnt, int FltH, int FltW );
static std::unique_ptr<CBlobConvolutionBase> GetProperInstance( IMathEngine* mathEngine, int FltCnt,
int channelCount, int filterHeight, int filterWidth, int sourceHeight, int sourceWidth,
int paddingHeight, int paddingWidth, int strideHeight, int strideWidth,
int dilationHeight, int dilationWidth, int resultHeight, int resultWidth, int resObjCnt );
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CBlobConvolutionFabric::IsBlobConvolutionAvailable( int FltCnt, int FltH, int FltW )
{
if( FltH % 2 == 0 || FltW % 2 == 0 ) {
return false;
}
if(
FltCnt == 32 ||
FltCnt == 24 ||
FltCnt == 18 ||
FltCnt == 6 ) {
return true;
}
return false;
}
std::unique_ptr<CBlobConvolutionBase> CBlobConvolutionFabric::GetProperInstance( IMathEngine* mathEngine, int filterCount,
int channelCount, int filterHeight, int filterWidth, int sourceHeight, int sourceWidth,
int paddingHeight, int paddingWidth, int strideHeight, int strideWidth,
int dilationHeight, int dilationWidth, int resultHeight, int resultWidth, int resObjCnt )
{
switch( filterCount ) {
case 32:
return std::unique_ptr<CBlobConvolutionBase>( new CBlobConvolution<32>( mathEngine,
channelCount, filterHeight, filterWidth, sourceHeight, sourceWidth,
paddingHeight, paddingWidth, strideHeight, strideWidth,
dilationHeight, dilationWidth, resultHeight, resultWidth, resObjCnt ) );
case 24:
return std::unique_ptr<CBlobConvolutionBase>( new CBlobConvolution<24>( mathEngine,
channelCount, filterHeight, filterWidth, sourceHeight, sourceWidth,
paddingHeight, paddingWidth, strideHeight, strideWidth,
dilationHeight, dilationWidth, resultHeight, resultWidth, resObjCnt ) );
case 18:
return std::unique_ptr<CBlobConvolutionBase>( new CBlobConvolution<18>( mathEngine,
channelCount, filterHeight, filterWidth, sourceHeight, sourceWidth,
paddingHeight, paddingWidth, strideHeight, strideWidth,
dilationHeight, dilationWidth, resultHeight, resultWidth, resObjCnt ) );
case 6:
return std::unique_ptr<CBlobConvolutionBase>( new CBlobConvolution<6>( mathEngine,
channelCount, filterHeight, filterWidth, sourceHeight, sourceWidth,
paddingHeight, paddingWidth, strideHeight, strideWidth,
dilationHeight, dilationWidth, resultHeight, resultWidth, resObjCnt ) );
default:
return nullptr;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<int FltCnt>
CBlobConvolution<FltCnt>::CBlobConvolution( IMathEngine* _mathEngine, int channelCount, int filterHeight, int filterWidth,
int sourceHeight, int sourceWidth, int paddingHeight, int paddingWidth, int strideHeight, int strideWidth,
int dilationHeight, int dilationWidth, int resultHeight, int resultWidth, int resObjCnt ) :
mathEngine( _mathEngine ),
ChCnt( channelCount ),
FltH( filterHeight ),
FltW( filterWidth ),
SrcH( sourceHeight ),
SrcW( sourceWidth ),
PaddingH( paddingHeight ),
PaddingW( paddingWidth ),
StrideH( strideHeight ),
StrideW( strideWidth ),
DilationH( dilationHeight ),
DilationW( dilationWidth ),
ResH( resultHeight ),
ResW( resultWidth ),
ResObjCnt( resObjCnt ),
src( nullptr ),
flt( nullptr ),
freeTerm( nullptr ),
res( nullptr ),
SrcLineStride( SrcW* ChCnt ),
SrcXStep( StrideW* ChCnt ),
SrcYStep( StrideH* SrcLineStride ),
SrcXDilation( DilationW* ChCnt ),
SrcYDilation( DilationH* SrcLineStride ),
SrcXWindowSize( FltW* SrcXDilation ),
ResLineStride( ResW* FltCnt ),
NarrowBatchProcessSize( getNarrowBatchProcessSize() ),
WideBatchProcessSize( getWideBatchProcessSize() )
{
// // Initialize PixelOffsetResStepsX, PixelOffsetResStepsY, SrcPixelsOffset and FltPixelsOffset
fillPixelOffset();
}
template<int FltCnt>
void CBlobConvolution<FltCnt>::ProcessConvolution( int threadCount,
const float* sourceData, const float* filterData, const float* freeTermData, float* resultData )
{
CFloatHandleStackVar filterTempBuffer( *mathEngine, FltW * FltH * FltCntM8 * ChCnt );
CFloatHandleStackVar freeTermTempBuffer( *mathEngine, FltCntM8 );
src = sourceData;
// Filter offset also are calculated from center
flt = rearrangeFilter( filterData, filterTempBuffer ) + ( FltW * FltH ) / 2 * ChCnt * FltCntM8;
freeTerm = rearrangeFreeTerm( freeTermData, freeTermTempBuffer );
res = resultData;
const int SrcObjSize = SrcW * SrcH * ChCnt;
const int ResObjSize = ResW * ResH * FltCnt;
const int ResRowCount = ResObjCnt * ResH;
const int curThreadCount = IsOmpRelevant( ResRowCount, ResRowCount * ResW * FltCnt * FltW * FltH * ChCnt ) ? threadCount : 1;
// Coordinates of the most top and left position of the center of the filter over the source image.
const int srcXOffset = FltW / 2 * DilationW - PaddingW;
const int srcYOffset = FltH / 2 * DilationH - PaddingH;
NEOML_OMP_NUM_THREADS( curThreadCount )
{
// Index of row in whole result array
int rowIdx;
// Count of rows for current thread
int rowCount;
if( OmpGetTaskIndexAndCount( ResRowCount, rowIdx, rowCount ) ) {
while( rowCount > 0 ) {
// Index of result image in output batch
int resIdx = rowIdx / ResH;
// Offset in current result image
int ryStart = rowIdx % ResH;
// Number of rows for processing ( or number of rows till the end of current result image ).
int ryCount = min( ResH - ryStart, rowCount );
rowIdx += ryCount;
rowCount -= ryCount;
// Pointers to src and res for current thread
const float* realSrcStart = src + resIdx * SrcObjSize + srcXOffset * ChCnt;
float* realResStart = res + resIdx * ResObjSize;
// Iterate through result, left->right, top->bottom
const int currentRH = min( ResH, ryStart + ryCount );
int ry = ryStart;
int yStep = 0;
// Iterate through all combination of intersections
for( int yStepIdx = 0; yStepIdx < PixelOffsetResStepsWidthY.size(); yStepIdx++ ) {
// Last index of res for current intersection.
yStep += PixelOffsetResStepsWidthY[yStepIdx];
// Process up to current step or up to and of current butch
int ryEnd = min( yStep, currentRH );
for( ; ry < ryEnd; ) {
const float* srcPtr = realSrcStart + srcYOffset * SrcLineStride + ry * SrcYStep;
float* resPtr = realResStart + ry * ResLineStride;
bool useNarrowProcessing = ryEnd - ry >= NarrowBatchProcessSize.Height;
size_t pixelsOffsetIdx = yStepIdx * PixelOffsetResStepsWidthX.size();
for( const auto& xStep : PixelOffsetResStepsWidthX ) {
processConvolutionLoop( xStep, useNarrowProcessing, srcPtr, resPtr, pixelsOffsetIdx );
pixelsOffsetIdx++;
}
ry += useNarrowProcessing ? NarrowBatchProcessSize.Height : WideBatchProcessSize.Height;
}
}
}
}
}
}
template<int FltCnt>
inline typename CBlobConvolution<FltCnt>::CSize CBlobConvolution<FltCnt>::getNarrowBatchProcessSize()
{
// Disable narrow processing by default
return { INT_MAX, INT_MAX };
}
template<int FltCnt>
inline void CBlobConvolution<FltCnt>::singleProcessNarrow( const float*, float*, size_t )
{
// dummy function
}
template<int FltCnt>
inline void CBlobConvolution<FltCnt>::processConvolutionLoop( int rxSize, bool useNarrowProcessing, const float*& srcPtr, float*& resPtr, size_t windowIndex )
{
const int batchStep = useNarrowProcessing ? NarrowBatchProcessSize.Width : WideBatchProcessSize.Width;
for( ; rxSize >= batchStep; rxSize -= batchStep ) {
batchProcess( srcPtr, resPtr, windowIndex, useNarrowProcessing );
srcPtr += batchStep * SrcXStep;
resPtr += batchStep * FltCnt;
}
if( useNarrowProcessing ) {
for( ; rxSize > 0; rxSize-- ) {
singleProcessNarrow( srcPtr, resPtr, windowIndex );
srcPtr += SrcXStep;
resPtr += FltCnt;
}
} else {
for( ; rxSize > 0; rxSize-- ) {
singleProcess( srcPtr, resPtr, windowIndex );
srcPtr += SrcXStep;
resPtr += FltCnt;
}
}
}
template<int FltCnt>
const float* CBlobConvolution<FltCnt>::rearrangeFilter( const float* filterData, CFloatHandleStackVar& filterTempBuffer )
{
// Rearrange filter data.
// Initial packing:
// Filter[0] Pixel[0] Channel[0-23]
// Filter[0] Pixel[1] Channel[0-23]
// ...
// Filter[0] Pixel[8] Channel[0-23]
// Filter[1] Pixel[0] Channel[0-23]
// ...
// Filter[23] Pixel[8] Channel[0-23]
//
// 1. Result packing for case when FltCnt == FltCntM8 (for example: 24):
// Pixel[0] Channel[0] Filter[0-23]
// Pixel[0] Channel[1] Filter[0-23]
// ...
// Pixel[0] Channel[23] Filter[0-23]
// Pixel[1] Channel[0] Filter[0-23]
// ...
// Pixel[8] Channel[23] Filter[0-23]
//
// 2. Result packing for case when FltCnt != FltCntM8 (for example: 18):
// Pixel[0] Channel[0] Filter[0-17] Filter[0-5]
// Pixel[0] Channel[1] Filter[0-23] Filter[0-5]
// ...
// Pixel[0] Channel[23] Filter[0-23] Filter[0-5]
// Pixel[1] Channel[0] Filter[0-23] Filter[0-5]
// ...
// Pixel[8] Channel[23] Filter[0-23] Filter[0-5]
float* resFilterStartPtr = static_cast< float* >( mathEngine->GetBuffer( filterTempBuffer.GetHandle(), 0, filterTempBuffer.Size() * sizeof( float ), false ) );
float* resFilter = resFilterStartPtr;
ASSERT_EXPR( reinterpret_cast< uintptr_t >( resFilter ) % AvxAlignment == 0 );
for( int y = 0; y < FltH; y++ ) {
for( int x = 0; x < FltW; x++ ) {
for( int c = 0; c < ChCnt; c++ ) {
const float* srcFilter = filterData + ( x + y * FltW ) * ChCnt + c;
for( int f = 0; f < FltCnt; f++ ) {
*resFilter++ = *srcFilter;
srcFilter += FltW * FltH * ChCnt;
}
if( FltCntM8 != FltCnt ) {
srcFilter = filterData + ( x + y * FltW ) * ChCnt + c;
for( int f = 0; f < FltCntM8 - FltCnt; f++ ) {
*resFilter++ = *srcFilter;
srcFilter += FltW * FltH * ChCnt;
}
}
}
}
}
return resFilterStartPtr;
}
template<int FltCnt>
const float* CBlobConvolution<FltCnt>::rearrangeFreeTerm( const float* freeTermData, CFloatHandleStackVar& freeTermTempBuffer )
{
if( freeTermData == nullptr ) {
return nullptr;
}
float* resFreeTermStartPtr = static_cast< float* >( mathEngine->GetBuffer( freeTermTempBuffer.GetHandle(), 0, freeTermTempBuffer.Size() * sizeof( float ), false ) );
float* resFreeTerm = resFreeTermStartPtr;
ASSERT_EXPR( reinterpret_cast< uintptr_t >( resFreeTerm ) % AvxAlignment == 0 );
for( int f = 0; f < FltCnt; f++ ) {
*resFreeTerm++ = *freeTermData++;
}
if( FltCnt != FltCntM8 ) {
freeTermData -= FltCnt;
for( int f = 0; f < FltCnt; f++ ) {
*resFreeTerm++ = *freeTermData++;
}
}
return resFreeTermStartPtr;
}
template<int FltCnt>
std::vector<int> CBlobConvolution<FltCnt>::getPixelOffsetSrcSteps( int srcDim, int fDim, int dDim, int sDim, int pDim )
{
vector<int> ret( fDim );
const int halfFDim = fDim / 2;
// First offset of center of the filter window (Take in consideration paddings)
const int firstOffset = halfFDim * dDim - pDim;
const int lastSrcPixelIdx = srcDim - 1;
// Last offset of center of the filter window (Take in consideration paddings)
// (lastSrcPixelIdx - 2 * firstOffset) - width of window
const int lastOffset = firstOffset + ( lastSrcPixelIdx - 2 * firstOffset ) / sDim * sDim;
ret[0] = firstOffset;
for( int i = 1; i <= halfFDim; i++ ) {
// up to middle
ret[i] = firstOffset + ( i * dDim - firstOffset + sDim - 1 ) / sDim * sDim;
}
for( int i = fDim - 1, j = 1; i > fDim / 2; i--, j++ ) {
// from last to next to middle
ret[i] = lastOffset - ( lastOffset + j * dDim - lastSrcPixelIdx ) / sDim * sDim + sDim;
}
sort( ret.begin(), ret.end() );
// Remove out of range and repeated items
auto start = ret.begin();
while( *start < 0 ) start++;
auto end = start;
auto tempIt = end + 1;
int lastSrcDim = srcDim - firstOffset - 1;
while( tempIt != ret.end() && *tempIt <= lastSrcDim ) {
if( *tempIt != *end ) {
int temp = *tempIt;
*( ++end ) = temp;
}
tempIt++;
}
end++;
return vector<int>( start, end );
}
template<int FltCnt>
void CBlobConvolution<FltCnt>::fillPixelOffset()
{
using namespace std;
vector<int> pixelOffsetSrcStepsX = getPixelOffsetSrcSteps( SrcW, FltW, DilationW, StrideW, PaddingW );
vector<int> pixelOffsetSrcStepsY = getPixelOffsetSrcSteps( SrcH, FltH, DilationH, StrideH, PaddingH );
// Calculate offset on the source image where intersection of filter and image is changed.
auto getPixelOffsetResStepsWidth = []( const std::vector<int>& pixelOffsetSrcSteps, int srcDim, int fDim, int dDim, int sDim, int pDim )
{
vector<int> ret( pixelOffsetSrcSteps.size() );
const int firstOffset = fDim / 2 * dDim - pDim;
const int lastSrcPixelIdx = srcDim - 1;
const int lastOffset = firstOffset + ( lastSrcPixelIdx - 2 * firstOffset ) / sDim * sDim;
int i = 0;
for( ; i < ret.size() - 1; i++ ) {
ret[i] = ( pixelOffsetSrcSteps[i + 1] - pixelOffsetSrcSteps[i] ) / sDim;
}
ret[i] = ( lastOffset - pixelOffsetSrcSteps[i] ) / sDim + 1;
return ret;
};
PixelOffsetResStepsWidthX = getPixelOffsetResStepsWidth( pixelOffsetSrcStepsX, SrcW, FltW, DilationW, StrideW, PaddingW );
PixelOffsetResStepsWidthY = getPixelOffsetResStepsWidth( pixelOffsetSrcStepsY, SrcH, FltH, DilationH, StrideH, PaddingH );
// Get size of intersection of filter window and source image
auto getFilterWindowSize = []( const vector<int>& pixelOffsetSrcSteps, int srcDim, int fDim, int dDim ) -> vector<pair<int, int>> {
// first - count of items in filter from center to top
// second - count of items in filter from center to bottom
vector<pair<int, int>> ret( pixelOffsetSrcSteps.size() );
for( int i = 0; i < pixelOffsetSrcSteps.size(); i++ ) {
const int halfFDim = fDim / 2;
ret[i] = make_pair(
min( pixelOffsetSrcSteps[i] / dDim, halfFDim ),
min( ( ( srcDim - 1 ) - pixelOffsetSrcSteps[i] ) / dDim, halfFDim ) );
}
return ret;
};
vector<pair<int, int>> offsetSizeX = getFilterWindowSize( pixelOffsetSrcStepsX, SrcW, FltW, DilationW );
vector<pair<int, int>> offsetSizeY = getFilterWindowSize( pixelOffsetSrcStepsY, SrcH, FltH, DilationH );
// Calculate resulted offsets of pixels in window.
auto fillPixelOffset = [&]( int hStride, int wStride ) ->vector<vector<int>> {
vector<vector<int>> offsets( offsetSizeX.size() * offsetSizeY.size() );
auto it = offsets.begin();
for( const auto& y : offsetSizeY ) {
for( const auto& x : offsetSizeX ) {
it->resize( ( x.first + x.second + 1 ) * ( y.first + y.second + 1 ) );
auto it_offt = it->begin();
for( int i = -y.first; i <= y.second; i++ ) {
for( int j = -x.first; j <= x.second; j++ ) {
*it_offt++ = i * hStride + j * wStride;
}
}
it++;
}
}
return offsets;
};
SrcPixelsOffset = fillPixelOffset( SrcYDilation, SrcXDilation );
FltPixelsOffset = fillPixelOffset( FltW * ChCnt * FltCntM8, ChCnt * FltCntM8 );
}
template<int FltCnt>
inline void CBlobConvolution<FltCnt>::rotateLeft6( __m256& y0, __m256& y1, __m256& y2 )
{ // y0 y1 y2
// 0 1 2 3 - 4 5 6 7 - 8 0 1 2
// 3 4 5 6 - 7 8 0 1 - 2 3 4 5
// 6 7 8 0 - 1 2 3 4 - 5 6 7 8
// before: 0 1 2 3
// after: 2 3 0 1
__m256 yt0 = _mm256_permute2f128_ps( y0, y0, _MM_SHUFFLE( 0, 0, 0, 1 ) );
// before: 4 5 6 7
// after: 6 7 4 5
__m256 yt1 = _mm256_permute2f128_ps( y1, y1, _MM_SHUFFLE( 0, 0, 0, 1 ) );
// before: 6 7 4 5|8 0 1 2
// after: 7 8 5 1
__m256 yt2 = _mm256_shuffle_ps( yt1, y2, _MM_SHUFFLE( 1, 0, 3, 2 ) );
// before: 2 3 0 1|6 7 4 5
// after: 2 3 4 5
y2 = _mm256_blend_ps( yt0, yt1, 0xf0 );
// before: 2 3 4 5|4 5 6 7
// after: 3 4 5 6
y0 = _mm256_shuffle_ps( y2, y1, _MM_SHUFFLE( 1, 0, 3, 2 ) );
// before: 7 8 5 1|2 3 0 1
// after: 7 8 0 1
y1 = _mm256_blend_ps( yt2, yt0, 0xf0 );
}
template<int FltCnt>
inline void CBlobConvolution<FltCnt>::rotateLeft2( __m256& y )
{
// 0 1 2 0
// 1 2 0 1
// 2 0 1 2
// before: 0 1 2 0
// after: 2 0 0 1
__m256 yt = _mm256_permute2f128_ps( y, y, _MM_SHUFFLE( 0, 0, 0, 1 ) );
// before: 0 1 2 0|2 0 0 1
// after: 1 2 0 0
y = _mm256_shuffle_ps( y, yt, _MM_SHUFFLE( 1, 0, 3, 2 ) );
// before: 1 2 0 0|2 0 0 1
// after: 1 2 0 1
y = _mm256_blend_ps( y, yt, 0xf0 );
}
} // namespace NeoML
#ifndef _mm256_set_m128
// This instruction is defined since 8 gcc in avxintrin.h
#define _mm256_set_m128( hi, lo) _mm256_insertf128_ps( _mm256_castps128_ps256( lo ), ( hi ), 0x1 )
#endif
// Class specializations
#include <BlobConvolution_FltCnt_6.h>
#include <BlobConvolution_FltCnt_18.h>
#include <BlobConvolution_FltCnt_24.h>
#include <BlobConvolution_FltCnt_32.h>
|
alokmenghrajani/ncipher_rust | demo/main.c | <reponame>alokmenghrajani/ncipher_rust
#include <stdio.h>
int rust_function(int);
int main(void) {
rust_function(10);
return 0;
}
|
bakercp/ofxIndexRange | libs/ofxIndexRange/include/ofx/IndexRange.h | <reponame>bakercp/ofxIndexRange
//
// Copyright (c) 2019 <NAME> <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#pragma once
#include <vector>
#include <iostream>
#include "json.hpp"
namespace ofx {
/// \brief An unsigned integral index range.
class IndexRange
{
public:
/// \brief Create a default empty range with location 0 and length 0.
IndexRange();
/// \brief Create an index range with the given location and length.
/// \param location The starting location of the range.
/// \param size The size of the range.
IndexRange(std::size_t location, std::size_t size);
/// \returns the location.
std::size_t getMin() const;
/// \brief Set the minimum location, keeping max.
///
/// Will adjust location and size to keep the current max and set a new min.
///
/// If new min > current max, min and max will be equal to \p value and size
/// will be set to zero.
///
/// \param value The new location of the minimum.
void setMin(std::size_t value);
/// \brief Get the maximum value in the range.
/// \note This value has overflowed when high() < low();
/// \returns the sum of location + size.
std::size_t getMax() const;
/// \brief Set the max location, keeping min.
///
/// Will adjust size and keep the current min.
///
/// If new max < current min, min and max will be equal to \p value and size
/// will become zero.
///
/// \param value The new location of the maximum.
void setMax(std::size_t value);
/// \returns true if max() < min().
bool overflows() const;
/// \returns true if the size is 0.
bool empty() const;
/// \brief Determine if a this range contains the location.
/// \param location The location to test.
/// \returns true if the location is within the range.
bool contains(std::size_t location) const;
/// \brief Determine if a this range contains the range.
/// \param other The range to test.
/// \returns true if the range contains the other range.
bool contains(const IndexRange& other) const;
/// \brief Determine if a range is adjacent on the low side of this range.
///
/// Adjacent ranges may not overlap. Adjacent ranges must have sizes > 0.
///
/// \param other The other range to check.
/// \returns true if the other range is adjacent on the low side.
bool isHighAdjacentTo(const IndexRange& other) const;
/// \brief Determine if a range is adjacent on the high side of this range.
///
/// Adjacent ranges may not overlap. Adjacent ranges must have sizes > 0.
///
/// \param other The other range to check.
/// \returns true if the other range is adjacent on the high side.
bool isLowAdjacentTo(const IndexRange& other) const;
/// \brief Determine if a range is adjacent on either side of this range.
/// \param other The other range to check.
/// \returns true if adjacentHigh(other) || adjacentLow(other).
bool isAdjacentTo(const IndexRange& other) const;
/// \brief Determine if this range intersects with the other.
/// \param other The other range to check.
/// \returns true if the ranges intersect.
bool intersects(const IndexRange& other) const;
/// \brief Determine the intersection of this range and the other.
/// \param other The other range to check.
/// \returns the intersection of the ranges. An intersection with length 0
/// means the ranges don't intersect.
IndexRange intersectionWith(const IndexRange& other) const;
/// \brief Determine the union of this range and the other.
/// \param other The other range to check.
/// \returns the union of the ranges. A union with length 0 means both
/// ranges were empty.
IndexRange unionWith(const IndexRange& other) const;
/// \brief Merge this IndexRange with another IndexRange.
///
/// If this IndexRange and the other intersect or are adjacent to each other
/// their union is returned.
///
/// \param other The range to attempt a merge with.
/// \returns a valid IndexRange if ranges intersect.
IndexRange mergeWith(const IndexRange& other) const;
/// \brief If an IndexRange is in an overflow state, truncate and return the remainder.
/// \returns the remainder of an overflow state or an IndexRange with size == 0.
IndexRange clearOverflow();
bool operator == (const IndexRange& other) const;
bool operator != (const IndexRange& other) const;
bool operator < (const IndexRange& other) const;
bool operator <= (const IndexRange& other) const;
bool operator > (const IndexRange& other) const;
bool operator >= (const IndexRange& other) const;
/// \brief Create an IndexRange from an inclusive interval [lower, upper].
///
/// An index range is constructed as follows:
///
/// if (upper < lower)
/// std::swap(lower, upper);
///
/// return IndexRange(lower, upper - lower + 1);
///
/// \param lower The low side of the interval.
/// \param upper The high side of the interval (inclusive).
/// \returns a valid IndexRange representing the inclusive interval.
static IndexRange fromInterval(std::size_t lower, std::size_t upper);
/// \brief Create an IndexRange from an exclusive interval [min, max).
///
/// An index range is constructed as follows:
///
/// if (max < min)
/// std::swap(min, max);
///
/// return IndexRange(min, max - min);
///
/// \param min The low side of the interval.
/// \param max The high side of the interval (exclusive).
/// \returns a valid IndexRange representing the inclusive interval.
static IndexRange fromExclusiveInterval(std::size_t min, std::size_t max);
/// \brief Alias for std::numeric_limits<std::size_t>::max().
static const std::size_t MAX;
/// \brief Alias for std::numeric_limits<std::size_t>::lowest().
static const std::size_t LOWEST;
/// \brief The largest range IndexRange(0, MAX).
static const IndexRange MAXIMUM_RANGE;
/// \brief The starting location of the Range.
std::size_t location = 0;
/// \brief The size of the Range.
std::size_t size = 0;
friend std::ostream& operator << (std::ostream& os, const IndexRange& range);
friend std::istream& operator >> (std::istream& is, IndexRange& range);
};
inline std::ostream& operator << (std::ostream& os, const IndexRange& range)
{
os << "{" << range.location << "," << range.size << "}";
return os;
}
inline std::istream& operator >> (std::istream& is, IndexRange& range)
{
is.ignore(1);
is >> range.location;
is.ignore(1);
is >> range.size;
is.ignore(1);
return is;
}
inline void to_json(nlohmann::json& j, const IndexRange& v)
{
j = { v.location, v.size };
}
inline void from_json(const nlohmann::json& j, IndexRange& v)
{
v.location = j[0];
v.size = j[1];
}
} // namespace ofx
|
bakercp/ofxIndexRange | libs/ofxIndexRange/include/ofx/IndexRangeList.h | <filename>libs/ofxIndexRange/include/ofx/IndexRangeList.h
//
// Copyright (c) 2019 <NAME> <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#pragma once
#include "ofx/IndexRange.h"
namespace ofx {
/// \brief A list for working with collections of index ranges.
///
/// Ranges can be added, removed, inserted and erased.
class IndexRangeList
{
public:
/// \brief Create a default empty IndexRangeList.
IndexRangeList();
/// \brief Create an IndexRangeList with the given ranges.
/// \param ranges The ranges to add.
IndexRangeList(const std::vector<IndexRange>& ranges);
/// \brief Destroy the IndexRangeList.
~IndexRangeList();
/// \brief Add the given range to the list.
///
/// If the added range overlaps with an existing range it will be merged.
///
/// The added range will be validated.
///
/// \param range The range to add.
void add(const IndexRange& range);
/// \brief Add the given range to the list.
///
/// If the removed range overlaps with an existing range all
/// intersecting portions will be removed.
///
/// \param range The range to remove.
void remove(const IndexRange& range);
/// \brief Expand and shift any matching matching range.
///
/// If a range covers this insertion index, the range's size
/// will be expanded. Then all subsequent ranges will have their locations
/// increased by size. Ranges that overflow during this shift will be
/// removed.
///
/// \param range The range to insert.
void insert(const IndexRange& range);
/// \brief Truncate and shift any matching ranges.
///
/// If an range is fully enclosed by the erased section, remove it.
/// If an range is partially covered by the erased section, truncate
/// it and shift down any subsequent ranges.
///
/// \param index The erase position.
/// \param size The size of the erased section.
void erase(const IndexRange& range);
/// \brief Clear all ranges.
void clear();
/// \returns true if there are no ranges.
bool empty() const;
/// \returns the number of ranges defined.
std::size_t size() const;
/// \returns the sorted, merged ranges.
std::vector<IndexRange> ranges() const;
/// \brief Get valid range.
///
/// All functions in the IndexRangeList use validated ranges.
///
/// A validated range is a range with no overflow.
///
/// \returns a well-formed range.
static IndexRange validate(const IndexRange& range);
private:
/// \brief Will sort _ranges.
void _sort() const;
/// \brief True if _ranges has been sorted via _sort().
mutable bool _sorted = false;
/// \brief The ranges.
mutable std::vector<IndexRange> _ranges;
};
} // namespace ofx
|
BlackCatDevel0per/pyaesni | libaesni/include/iaesni.h | /*
* Copyright (c) 2010, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* 2016, <NAME> (<EMAIL>) */
#ifndef IAESNI_H
#define IAESNI_H
#include <libaesni_export.h>
#include <stdlib.h>
/* indicates input param */
#define IAES_IN
/* indicates output param */
#define IAES_OUT
/* indicates input/output param - based on context */
#define IAES_INOUT
#define IAES_BLOCK_SIZE 16 /*in bytes*/
#define IAES_128_KEYSIZE 16 /*in bytes*/
#define IAES_192_KEYSIZE 24 /*in bytes*/
#define IAES_256_KEYSIZE 32 /*in bytes*/
typedef unsigned char UCHAR;
#ifdef __cplusplus
extern "C" {
#endif
/* test if the processor actually supports the above functions */
/* executing one the functions below without processor support will cause UD fault */
/* bool check_for_aes_instructions(void); */
LIBAESNI_EXPORT int check_for_aes_instructions(void);
/* encryption functions */
/* plainText is pointer to input stream */
/* cipherText is pointer to buffer to be filled with encrypted (cipher text) data */
/* key is pointer to enc key (sizes are 16 bytes for AES-128, 24 bytes for AES-192, 32 for AES-256) */
/* numBlocks is number of 16 bytes blocks to process - note that encryption is done of full 16 byte blocks */
LIBAESNI_EXPORT void intel_AES_enc128(IAES_IN const UCHAR *plainText, IAES_OUT UCHAR *cipherText, IAES_IN const UCHAR key[IAES_128_KEYSIZE], IAES_IN size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc192(IAES_IN const UCHAR *plainText, IAES_OUT UCHAR *cipherText, IAES_IN const UCHAR key[IAES_192_KEYSIZE], IAES_IN size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc256(IAES_IN const UCHAR *plainText, IAES_OUT UCHAR *cipherText, IAES_IN const UCHAR key[IAES_256_KEYSIZE], IAES_IN size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc256_IGE(const UCHAR *plainText, UCHAR *cipherText, const UCHAR key[IAES_256_KEYSIZE], const UCHAR iv[2 * IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc128_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR key[IAES_128_KEYSIZE], const UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc192_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR key[IAES_192_KEYSIZE], const UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_enc256_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR key[IAES_256_KEYSIZE], const UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
/* encryption functions */
/* cipherText is pointer to encrypted stream */
/* plainText is pointer to buffer to be filled with original (plain text) data */
/* key is pointer to enc key (sizes are 16 bytes for AES-128, 24 bytes for AES-192, 32 for AES-256) */
/* numBlocks is number of 16 bytes blocks to process - note that decryption is done of full 16 byte blocks */
LIBAESNI_EXPORT void intel_AES_dec128(IAES_IN const UCHAR *cipherText, IAES_OUT UCHAR *plainText, IAES_IN const UCHAR key[IAES_128_KEYSIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec192(IAES_IN const UCHAR *cipherText, IAES_OUT UCHAR *plainText, IAES_IN const UCHAR key[IAES_192_KEYSIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec256(IAES_IN const UCHAR *cipherText, IAES_OUT UCHAR *plainText, IAES_IN const UCHAR key[IAES_256_KEYSIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec256_IGE(const UCHAR *cipherText, UCHAR *plainText, const UCHAR key[IAES_256_KEYSIZE], const UCHAR iv[2 * IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec128_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR key[IAES_128_KEYSIZE], IAES_INOUT UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec192_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR key[IAES_192_KEYSIZE], IAES_INOUT UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_dec256_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR key[IAES_256_KEYSIZE], IAES_INOUT UCHAR iv[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_encdec128_CTR(const UCHAR *input, UCHAR *output, const UCHAR key[IAES_128_KEYSIZE], IAES_INOUT UCHAR ic[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_encdec192_CTR(const UCHAR *input, UCHAR *output, const UCHAR key[IAES_192_KEYSIZE], IAES_INOUT UCHAR ic[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT void intel_AES_encdec256_CTR(const UCHAR *input, UCHAR *output, const UCHAR key[IAES_256_KEYSIZE], IAES_INOUT UCHAR ic[IAES_BLOCK_SIZE], size_t numBlocks);
LIBAESNI_EXPORT unsigned long long intel_AES_rdtsc(void);
#ifdef __cplusplus
}
#endif
#endif /* IAESNI_H */
|
BlackCatDevel0per/pyaesni | pyaesni.c |
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <iaesni.h>
static PyObject *ige(PyObject *args, uint8_t encrypt) {
Py_buffer data, key, iv;
uint8_t *buf;
PyObject *out;
if (!PyArg_ParseTuple(args, "y*y*y*", &data, &key, &iv))
return NULL;
if (data.len == 0) {
PyErr_SetString(PyExc_ValueError, "Data must not be empty");
return NULL;
}
if (data.len % 16 != 0) {
PyErr_SetString(PyExc_ValueError, "Data size must match a multiple of 16 bytes");
return NULL;
}
if (key.len != 32) {
PyErr_SetString(PyExc_ValueError, "Key size must be exactly 32 bytes");
return NULL;
}
if (iv.len != 32) {
PyErr_SetString(PyExc_ValueError, "IV size must be exactly 32 bytes");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
buf = malloc(data.len);
if (encrypt) {
/*buf = ige256(data.buf, data.len, key.buf, iv.buf, encrypt);*/
intel_AES_enc256_IGE(data.buf, buf, key.buf, iv.buf, data.len / 16);
} else {
intel_AES_dec256_IGE(data.buf, buf, key.buf, iv.buf, data.len / 16);
}
Py_END_ALLOW_THREADS
PyBuffer_Release(&data);
PyBuffer_Release(&key);
PyBuffer_Release(&iv);
out = Py_BuildValue("y#", buf, data.len);
free(buf);
return out;
}
static PyObject *ige256_encrypt(PyObject *self, PyObject *args) {
return ige(args, 1);
}
static PyObject *ige256_decrypt(PyObject *self, PyObject *args) {
return ige(args, 0);
}
static PyObject *ctr256_encrypt(PyObject *self, PyObject *args) {
Py_buffer data, key, iv, state;
uint8_t *buf;
PyObject *out;
if (!PyArg_ParseTuple(args, "y*y*y*y*", &data, &key, &iv, &state))
return NULL;
if (data.len == 0) {
PyErr_SetString(PyExc_ValueError, "Data must not be empty");
return NULL;
}
if (key.len != 32) {
PyErr_SetString(PyExc_ValueError, "Key size must be exactly 32 bytes");
return NULL;
}
if (iv.len != 16) {
PyErr_SetString(PyExc_ValueError, "IV size must be exactly 16 bytes");
return NULL;
}
/* if (state.len != 1) {
PyErr_SetString(PyExc_ValueError, "State size must be exactly 1 byte");
return NULL;
}*/
/*if (*(uint8_t *) state.buf > 15) {
PyErr_SetString(PyExc_ValueError, "State value must be in the range [0, 15]");
return NULL;
}*/
Py_BEGIN_ALLOW_THREADS
buf = malloc(data.len);
/* buf = ctr256(data.buf, data.len, key.buf, iv.buf, state.buf);*/
intel_AES_encdec256_CTR(data.buf, buf, key.buf, iv.buf, data.len / 16);
Py_END_ALLOW_THREADS
PyBuffer_Release(&data);
PyBuffer_Release(&key);
PyBuffer_Release(&iv);
out = Py_BuildValue("y#", buf, data.len);
free(buf);
return out;
}
static PyObject *cbc(PyObject *args, uint8_t encrypt) {
Py_buffer data, key, iv;
uint8_t *buf;
PyObject *out;
if (!PyArg_ParseTuple(args, "y*y*y*", &data, &key, &iv))
return NULL;
if (data.len == 0) {
PyErr_SetString(PyExc_ValueError, "Data must not be empty");
return NULL;
}
if (data.len % 16 != 0) {
PyErr_SetString(PyExc_ValueError, "Data size must match a multiple of 16 bytes");
return NULL;
}
if (key.len != 32) {
PyErr_SetString(PyExc_ValueError, "Key size must be exactly 32 bytes");
return NULL;
}
if (iv.len != 16) {
PyErr_SetString(PyExc_ValueError, "IV size must be exactly 16 bytes");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
/*buf = cbc256(data.buf, data.len, key.buf, iv.buf, encrypt);*/
buf = malloc(data.len);
if (encrypt) {
intel_AES_enc256_CBC(data.buf, buf, key.buf, iv.buf, data.len / 16);
}
else {
intel_AES_dec256_CBC(data.buf, buf, key.buf, iv.buf, data.len / 16);
}
Py_END_ALLOW_THREADS
PyBuffer_Release(&data);
PyBuffer_Release(&key);
PyBuffer_Release(&iv);
out = Py_BuildValue("y#", buf, data.len);
free(buf);
return out;
}
static PyObject *cbc256_encrypt(PyObject *self, PyObject *args) {
return cbc(args, 1);
}
static PyObject *cbc256_decrypt(PyObject *self, PyObject *args) {
return cbc(args, 0);
}
static PyMethodDef methods[] = {
{"ige256_encrypt", (PyCFunction) ige256_encrypt, METH_VARARGS, "AES256-IGE Encryption"},
{"ige256_decrypt", (PyCFunction) ige256_decrypt, METH_VARARGS, "AES256-IGE Decryption"},
{"ctr256_encrypt", (PyCFunction) ctr256_encrypt, METH_VARARGS, "AES256-CTR Encryption"},
{"ctr256_decrypt", (PyCFunction) ctr256_encrypt, METH_VARARGS, "AES256-CTR Decryption"},
{"cbc256_encrypt", (PyCFunction) cbc256_encrypt, METH_VARARGS, "AES256-CBC Encryption"},
{"cbc256_decrypt", (PyCFunction) cbc256_decrypt, METH_VARARGS, "AES256-CBC Decryption"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"pyaesni",
"libaesni wrapper",
-1,
methods
};
PyMODINIT_FUNC PyInit_pyaesni(void) {
return PyModule_Create(&module);
}
|
BlackCatDevel0per/pyaesni | libaesni/test/test_libaesni.c | #include <iaesni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Test vectors based on NIST Recommendation for Block Cipher Modes of Operation
// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
unsigned char test_plain_text[64] = { 0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a,
0xae,0x2d,0x8a,0x57,0x1e,0x03,0xac,0x9c,0x9e,0xb7,0x6f,0xac,0x45,0xaf,0x8e,0x51,
0x30,0xc8,0x1c,0x46,0xa3,0x5c,0xe4,0x11,0xe5,0xfb,0xc1,0x19,0x1a,0x0a,0x52,0xef,
0xf6,0x9f,0x24,0x45,0xdf,0x4f,0x9b,0x17,0xad,0x2b,0x41,0x7b,0xe6,0x6c,0x37,0x10};
unsigned char test_key_256[32] = { 0x60,0x3d,0xeb,0x10,0x15,0xca,0x71,0xbe,0x2b,0x73,0xae,0xf0,0x85,0x7d,0x77,0x81,
0x1f,0x35,0x2c,0x07,0x3b,0x61,0x08,0xd7,0x2d,0x98,0x10,0xa3,0x09,0x14,0xdf,0xf4};
unsigned char test_init_vector[16] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
unsigned char test_cipher_256_cbc[64]={ 0xf5,0x8c,0x4c,0x04,0xd6,0xe5,0xf1,0xba,0x77,0x9e,0xab,0xfb,0x5f,0x7b,0xfb,0xd6,
0x9c,0xfc,0x4e,0x96,0x7e,0xdb,0x80,0x8d,0x67,0x9f,0x77,0x7b,0xc6,0x70,0x2c,0x7d,
0x39,0xf2,0x33,0x69,0xa9,0xd9,0xba,0xcf,0xa5,0x30,0xe2,0x63,0x04,0x23,0x14,0x61,
0xb2,0xeb,0x05,0xe2,0xc3,0x9b,0xe9,0xfc,0xda,0x6c,0x19,0x07,0x8c,0x6a,0x9d,0x1b};
void printhex(const unsigned char *s, size_t size){
for (const unsigned char *end = s + size; s < end; s++) {
printf("%x", *s);
}
putchar('\n');
}
void test_cbc_256(){
unsigned int buffer_size = 64;
int nbocks = 4;
unsigned int i;
unsigned char *testVector = malloc(buffer_size);
unsigned char *testResult = malloc(buffer_size);
unsigned char test_iv[16];
for (i=0;i<buffer_size;i++)
{
testVector[i] = test_plain_text[i];
testResult[i] = 0xee;
}
memcpy(test_iv, test_init_vector, 16);
printf("IV value before the call: ");
printhex(test_iv, sizeof(test_iv));
enc_256_CBC(testVector, testResult, test_key_256, test_iv, nbocks);
printf("IV value after the call: ");
printhex(test_iv, sizeof(test_iv));
for (i=0;i<buffer_size;i++)
{
if (testResult[i] != test_cipher_256_cbc[i])
{
printf("AES-CBC-256 Encryption Failed\n");
}
}
memcpy(test_iv,test_init_vector,16);
dec_256_CBC(testResult,testVector,test_key_256, test_iv, nbocks);
for (i=0;i<buffer_size;i++)
{
if (testVector[i] != test_plain_text[i])
{
printf("AES-CBC-256 Decryption Failed\n");
}
}
printf("AES-CBC-256 Successful\n");
free(testVector);
free(testResult);
}
int main(){
int AES_ENABLED = check_for_aes_instructions();
if (AES_ENABLED == 1){
printf ("The CPU supports AES-NI\n");
test_cbc_256();
return EXIT_SUCCESS;
}
else{
printf ("The CPU seems to not support AES-NI\n");
return EXIT_FAILURE;
}
}
|
BlackCatDevel0per/pyaesni | libaesni/src/iaesni.c | /*
* Copyright (c) 2010, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* 2016, <NAME> (<EMAIL>) */
#include <string.h>
#include <iaesni.h>
#include "iaes_asm_interface.h"
#ifdef _WIN32
#include <intrin.h> /* __cpuid */
#else
#include <cpuid.h>
#endif
#if defined(_MSC_VER)
#ifdef ROUND_KEYS_UNALIGNED_TESTING
#define DEFINE_ROUND_KEYS \
__declspec(align(16)) UCHAR _expandedKey[16 * 16]; \
UCHAR *expandedKey = _expandedKey + 4;
#else
#define DEFINE_ROUND_KEYS \
__declspec(align(16)) UCHAR _expandedKey[16 * 16]; \
UCHAR *expandedKey = _expandedKey;
#endif
#elif defined(__GNUC__) || defined(__clang__) || (defined(__has_attribute) && __has_attribute(aligned))
#ifdef ROUND_KEYS_UNALIGNED_TESTING
#define DEFINE_ROUND_KEYS \
UCHAR __attribute__((aligned(16))) _expandedKey[16 * 16]; \
UCHAR *expandedKey = _expandedKey + 4;
#else
#define DEFINE_ROUND_KEYS \
UCHAR __attribute__((aligned(16))) _expandedKey[16 * 16]; \
UCHAR *expandedKey = _expandedKey;
#endif
#else
#error "Can't find any align extension"
#endif
#define AES_INSTRUCTIONS_CPUID_BIT (1 << 25)
static void iaesni_cpuid(unsigned int res[4], int leaf) {
#ifdef _WIN32
__cpuid((int *) res, leaf);
#else
__cpuid(leaf, res[0], res[1], res[2], res[3]);
#endif
}
/*
* check_for_aes_instructions()
* return 1 if cpu supports AES-NI, 0 otherwise
*/
int check_for_aes_instructions(void) { /*eax|ebx|ecx|edx*/
unsigned int cpuid_results[4] = {0, 0, 0, 0};
/* leaf 0 returns vendor string */
iaesni_cpuid(cpuid_results, 0);
/*
* MSB LSB
* EBX = 'u' 'n' 'e' 'G'
* EDX = 'I' 'e' 'n' 'i'
* ECX = 'l' 'e' 't' 'n'
*/
/* swap 2 and 3 register values to make them appear as EBX EDX ECX */
{
unsigned tmp = cpuid_results[2];
cpuid_results[2] = cpuid_results[3];
cpuid_results[3] = tmp;
}
if (cpuid_results[0] < 1) {
return 0;
}
/* check cpu vendor */
if (memcmp(&cpuid_results[1], "GenuineIntel", sizeof(*cpuid_results) * 3) != 0 && memcmp(&cpuid_results[1], "AuthenticAMD", sizeof(*cpuid_results) * 3) != 0) {
return 0;
}
/* leaf 1 returns cpu info, ecx contains feature flag we're interested in */
iaesni_cpuid(cpuid_results, 1);
if (cpuid_results[2] & AES_INSTRUCTIONS_CPUID_BIT) {
return 1;
}
return 0;
}
void intel_AES_enc128(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iEncExpandKey128(key, expandedKey);
iEnc128(&aesData);
}
void intel_AES_enc128_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, const UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = (UCHAR *) iv;
iEncExpandKey128(key, expandedKey);
iEnc128_CBC(&aesData);
}
void intel_AES_enc192(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iEncExpandKey192(key, expandedKey);
iEnc192(&aesData);
}
void intel_AES_enc192_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, const UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = (UCHAR *) iv;
iEncExpandKey192(key, expandedKey);
iEnc192_CBC(&aesData);
}
void intel_AES_enc256(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iEncExpandKey256(key, expandedKey);
iEnc256(&aesData);
}
void intel_AES_enc256_CBC(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, const UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = plainText;
aesData.out_block = cipherText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = (UCHAR *) iv;
iEncExpandKey256(key, expandedKey);
iEnc256_CBC(&aesData);
}
void intel_AES_dec128(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iDecExpandKey128(key, expandedKey);
iDec128(&aesData);
}
void intel_AES_dec128_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = iv;
iDecExpandKey128(key, expandedKey);
iDec128_CBC(&aesData);
}
void intel_AES_dec192(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iDecExpandKey192(key, expandedKey);
iDec192(&aesData);
}
void intel_AES_dec192_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = iv;
iDecExpandKey192(key, expandedKey);
iDec192_CBC(&aesData);
}
void intel_AES_dec256(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
iDecExpandKey256(key, expandedKey);
iDec256(&aesData);
}
void intel_AES_dec256_CBC(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, UCHAR *iv, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = cipherText;
aesData.out_block = plainText;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = iv;
iDecExpandKey256(key, expandedKey);
iDec256_CBC(&aesData);
}
void intel_AES_encdec256_CTR(const UCHAR *input, UCHAR *output, const UCHAR *key, UCHAR *ic, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = input;
aesData.out_block = output;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = ic;
iEncExpandKey256(key, expandedKey);
iEnc256_CTR(&aesData);
}
void intel_AES_encdec192_CTR(const UCHAR *input, UCHAR *output, const UCHAR *key, UCHAR *ic, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = input;
aesData.out_block = output;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = ic;
iEncExpandKey192(key, expandedKey);
iEnc192_CTR(&aesData);
}
void intel_AES_encdec128_CTR(const UCHAR *input, UCHAR *output, const UCHAR *key, UCHAR *ic, size_t numBlocks) {
DEFINE_ROUND_KEYS
sAesData aesData;
aesData.in_block = input;
aesData.out_block = output;
aesData.expanded_key = expandedKey;
aesData.num_blocks = numBlocks;
aesData.iv = ic;
iEncExpandKey128(key, expandedKey);
iEnc128_CTR(&aesData);
}
typedef unsigned long long i_aes_64;
typedef i_aes_64 i_aes_128[2];
static void intel_AES_encdec256_IGE_(const UCHAR *input, UCHAR *output, const UCHAR *key, const UCHAR *iv, size_t numBlocks, int encrypt) {
DEFINE_ROUND_KEYS
const i_aes_128 *in = (const i_aes_128 *) input;
i_aes_128 *out = (i_aes_128 *) output;
i_aes_128 iv1_block, iv2_block;
ExpandFunc expand_func = (encrypt)
? iEncExpandKey256
: iDecExpandKey256;
CryptoFunc crypto_func = (encrypt)
? iEnc256
: iDec256;
sAesData aesData;
expand_func(key, expandedKey);
aesData.expanded_key = expandedKey;
aesData.num_blocks = 1;
memcpy((encrypt) ? iv1_block : iv2_block, iv, sizeof(iv1_block));
memcpy((encrypt) ? iv2_block : iv1_block, iv + sizeof(iv2_block), sizeof(iv2_block));
for (size_t i = 0; i < numBlocks; i++, in++, out++) {
i_aes_128 in_block, out_block, iv2_block_tmp;
memcpy(in_block, in, sizeof(in_block)); /* this copy is mandatory, `in` can be unaligned */
iv2_block_tmp[0] = in_block[0];
iv2_block_tmp[1] = in_block[1];
in_block[0] ^= iv1_block[0];
in_block[1] ^= iv1_block[1];
aesData.in_block = (const UCHAR *) in_block;
aesData.out_block = (UCHAR *) out_block;
crypto_func(&aesData);
out_block[0] ^= iv2_block[0];
out_block[1] ^= iv2_block[1];
memcpy(out, out_block, sizeof(out_block));
iv1_block[0] = out_block[0];
iv1_block[1] = out_block[1];
iv2_block[0] = iv2_block_tmp[0];
iv2_block[1] = iv2_block_tmp[1];
}
}
void intel_AES_enc256_IGE(const UCHAR *plainText, UCHAR *cipherText, const UCHAR *key, const UCHAR *iv, size_t numBlocks) {
intel_AES_encdec256_IGE_(plainText, cipherText, key, iv, numBlocks, 1);
}
void intel_AES_dec256_IGE(const UCHAR *cipherText, UCHAR *plainText, const UCHAR *key, const UCHAR *iv, size_t numBlocks) {
intel_AES_encdec256_IGE_(cipherText, plainText, key, iv, numBlocks, 0);
}
unsigned long long intel_AES_rdtsc(void) {
return do_rdtsc();
}
|
BlackCatDevel0per/pyaesni | libaesni/src/iaes_asm_interface.h | <gh_stars>0
/*
* Copyright (c) 2010, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* 2016, <NAME> (<EMAIL>) */
#ifndef _INTEL_AES_ASM_INTERFACE_H__
#define _INTEL_AES_ASM_INTERFACE_H__
/* structure to pass aes processing data to asm level functions */
typedef struct sAesData_ {
IAES_IN const UCHAR *in_block;
IAES_OUT UCHAR *out_block;
IAES_IN const UCHAR *expanded_key;
IAES_INOUT UCHAR *iv; /* for CBC, CTR and IGE modes */
IAES_IN size_t num_blocks;
} sAesData;
typedef void (*ExpandFunc)(const UCHAR *, UCHAR *);
typedef void (*CryptoFunc)(sAesData *);
#ifdef __cplusplus
extern "C" {
#endif
#if 0
#define MYSTDCALL __stdcall
#else
#define MYSTDCALL
#endif
/* on apple it expects symbols to already have underscores */
#if !defined(__APPLE__) && !(defined(_WIN32) && !defined(_WIN64))
#define iEncExpandKey256 _iEncExpandKey256
#define iEncExpandKey192 _iEncExpandKey192
#define iEncExpandKey128 _iEncExpandKey128
#define iDecExpandKey256 _iDecExpandKey256
#define iDecExpandKey192 _iDecExpandKey192
#define iDecExpandKey128 _iDecExpandKey128
#define iEnc128 _iEnc128
#define iDec128 _iDec128
#define iEnc256 _iEnc256
#define iDec256 _iDec256
#define iEnc192 _iEnc192
#define iDec192 _iDec192
#define iEnc128_CBC _iEnc128_CBC
#define iDec128_CBC _iDec128_CBC
#define iEnc256_CBC _iEnc256_CBC
#define iDec256_CBC _iDec256_CBC
#define iEnc192_CBC _iEnc192_CBC
#define iDec192_CBC _iDec192_CBC
#define iEnc128_CTR _iEnc128_CTR
#define iEnc192_CTR _iEnc192_CTR
#define iEnc256_CTR _iEnc256_CTR
#define do_rdtsc _do_rdtsc
#endif
/* preparing the different key rounds, for enc/dec in asm */
/* expanded key should be 16-byte aligned */
/* expanded key should have enough space to hold all key rounds (16 bytes per round) - 256 bytes would cover all cases (AES256 has 14 rounds + 1 xor) */
void MYSTDCALL iEncExpandKey256(IAES_IN const UCHAR key[IAES_256_KEYSIZE], IAES_OUT UCHAR *expanded_key);
void MYSTDCALL iEncExpandKey192(IAES_IN const UCHAR key[IAES_192_KEYSIZE], IAES_OUT UCHAR *expanded_key);
void MYSTDCALL iEncExpandKey128(IAES_IN const UCHAR key[IAES_128_KEYSIZE], IAES_OUT UCHAR *expanded_key);
void MYSTDCALL iDecExpandKey256(const UCHAR key[IAES_256_KEYSIZE], IAES_OUT UCHAR *expanded_key);
void MYSTDCALL iDecExpandKey192(const UCHAR key[IAES_192_KEYSIZE], IAES_OUT UCHAR *expanded_key);
void MYSTDCALL iDecExpandKey128(const UCHAR key[IAES_128_KEYSIZE], IAES_OUT UCHAR *expanded_key);
/* enc/dec asm functions */
void MYSTDCALL iEnc128(sAesData *data);
void MYSTDCALL iDec128(sAesData *data);
void MYSTDCALL iEnc256(sAesData *data);
void MYSTDCALL iDec256(sAesData *data);
void MYSTDCALL iEnc192(sAesData *data);
void MYSTDCALL iDec192(sAesData *data);
void MYSTDCALL iEnc128_CBC(sAesData *data);
void MYSTDCALL iDec128_CBC(sAesData *data);
void MYSTDCALL iEnc256_CBC(sAesData *data);
void MYSTDCALL iDec256_CBC(sAesData *data);
void MYSTDCALL iEnc192_CBC(sAesData *data);
void MYSTDCALL iDec192_CBC(sAesData *data);
void MYSTDCALL iEnc128_CTR(sAesData *data);
void MYSTDCALL iEnc256_CTR(sAesData *data);
void MYSTDCALL iEnc192_CTR(sAesData *data);
/* rdtsc function */
unsigned long long do_rdtsc(void);
#ifdef __cplusplus
}
#endif
#endif
|
gaborcsardi/rim | Rig.app/Rig/rig-Bridging-Header.h | <reponame>gaborcsardi/rim
//
// rig-Bridging-Header.h
// Rig
//
// Created by <NAME> on 5/13/22.
//
#include "rig.h"
|
gaborcsardi/rim | Rig.app/Rig/rig.h | #include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
int rig_last_error(char *ptr, size_t size);
int rig_get_default(char *ptr, size_t size);
int rig_list(char *ptr, size_t size);
int rig_list_with_versions(char *ptr, size_t size);
int rig_set_default(const char *ptr);
int rig_start_rstudio(const char *pversion, const char *pproject);
int rig_library_list(char *ptr, size_t size);
int rig_lib_set_default(const char *ptr);
|
ooooo-youwillsee/leetcode | 0239-Sliding-Window-Maximum/cpp_0239/Solution1.h | <filename>0239-Sliding-Window-Maximum/cpp_0239/Solution1.h
//
// Created by ooooo on 2019/11/1.
//
#ifndef CPP_0239_SOLUTION1_H
#define CPP_0239_SOLUTION1_H
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
vector<int> res;
if (nums.size() < k) {
return res;
}
deque<int> q;
for (int i = 0, len = nums.size(); i < len; ++i) {
if (!q.empty() && q.front() <= i - k) {
q.pop_front();
}
while (!q.empty() && nums[q.back()] < nums[i]) {
q.pop_back();
}
q.push_back(i);
if (i >= k - 1) {
res.push_back(nums[q.front()]);
}
}
return res;
}
};
#endif //CPP_0239_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_005/cpp_005/Solution1.h | //
// Created by ooooo on 2020/3/6.
//
#ifndef CPP_005__SOLUTION1_H_
#define CPP_005__SOLUTION1_H_
#include <iostream>
#include <sstream>
using namespace std;
class Solution {
public:
string replaceSpace(string s) {
stringstream ss;
for (auto &c: s) {
if (c == ' ') ss << "%20";
else ss << c;
}
return ss.str();
}
};
#endif //CPP_005__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0687-Longest-Univalue-Path/cpp_0687/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/4.
//
#ifndef CPP_0687_SOLUTION1_H
#define CPP_0687_SOLUTION1_H
#include "TreeNode.h"
class Solution {
public:
int ans = 0;
int dfs(TreeNode *node) {
if (!node)return 0;
int leftLen = dfs(node->left);
int rightLen = dfs(node->right);
int left = 0, right = 0;
if (node->left && node->left->val == node->val) {
left += leftLen + 1;
}
if (node->right && node->right->val == node->val) {
right += rightLen + 1;
}
ans = max(ans, left + right);
// 父节点和子节点不一样, 可以直接返回0, 因为最大同值路径在ans中已经比较了
return max(left, right);
}
int longestUnivaluePath(TreeNode *root) {
dfs(root);
return ans;
}
};
#endif //CPP_0687_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_018/cpp_018/Solution3.h | <reponame>ooooo-youwillsee/leetcode<filename>lcof_018/cpp_018/Solution3.h
//
// Created by ooooo on 2020/3/13.
//
#ifndef CPP_018__SOLUTION3_H_
#define CPP_018__SOLUTION3_H_
#include "ListNode.h"
/**
* recursion
*/
class Solution {
public:
ListNode *deleteNode(ListNode *head, int val) {
if (!head) return nullptr;
if (head->val == val) return head->next;
head->next = deleteNode(head->next, val);
return head;
}
};
#endif //CPP_018__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0518-Coin Change 2/cpp_0518/Solution3.h | /**
* @author ooooo
* @date 2021/2/17 19:23
*/
#ifndef CPP_0518__SOLUTION3_H_
#define CPP_0518__SOLUTION3_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int change(int amount, vector<int> &coins) {
int n = coins.size();
vector<int> dp(amount + 1, 0);
// 没有任何金币,可以组合为0
dp[0] = 1;
for (auto coin : coins) {
for (int i = 1; i <= amount; ++i) {
if (i - coin >= 0) {
dp[i] += dp[i - coin];
}
}
}
return dp[amount];
}
};
#endif //CPP_0518__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 1863-Sum of All Subset XOR Totals/cpp_1863/Solution1.h | /**
*
* @author ooooo
* @date 2021/5/25 22:13
*/
#ifndef CPP_1863__SOLUTION1_H_
#define CPP_1863__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int ans = 0;
void dfs(vector<int> &nums, int i, int sum) {
ans += sum;
for (int j = i; j < nums.size(); j++) {
dfs(nums, j + 1, sum ^ nums[j]);
}
}
int subsetXORSum(vector<int> &nums) {
dfs(nums, 0, 0);
return ans;
};
};
#endif //CPP_1863__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0767-Reorganize String/cpp_0767/Solution1.h | <filename>0767-Reorganize String/cpp_0767/Solution1.h<gh_stars>10-100
/**
* @author ooooo
* @date 2020/11/30 17:53
*/
#ifndef CPP_0767__SOLUTION1_H_
#define CPP_0767__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
string reorganizeString(string S) {
vector<int> vec(26, 0);
int max_count = 0;
for (auto &c : S) {
vec[c - 'a']++;
max_count = max(max_count, vec[c - 'a']);
}
if (max_count > (S.size() + 1) / 2) {
return "";
}
auto f = [&](const char &c1, const char &c2) {
return vec[c1 - 'a'] < vec[c2 - 'a'];
};
priority_queue<char, vector<char>, decltype(f)> q(f);
for (int i = 0; i < 26; ++i) {
if (vec[i] > 0) {
q.push(i + 'a');
}
}
string ans = "";
while (q.size() > 1) {
char a = q.top();
q.pop();
ans.push_back(a);
char b = q.top();
q.pop();
ans.push_back(b);
vec[a - 'a']--;
vec[b - 'a']--;
if (vec[a - 'a'] > 0) {
q.push(a);
}
if (vec[b - 'a'] > 0) {
q.push(b);
}
}
if (!q.empty()) {
ans.push_back(q.top());
q.pop();
}
return ans;
}
};
#endif //CPP_0767__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0933-Number-of-Recent-Calls/cpp_0933/Solution1.h | //
// Created by ooooo on 2020/1/5.
//
#ifndef CPP_0933_SOLUTION1_H
#define CPP_0933_SOLUTION1_H
#include <iostream>
#include <queue>
using namespace std;
class RecentCounter {
private:
queue<int> q;
public:
RecentCounter() {
}
int ping(int t) {
q.push(t);
while (!q.empty() && q.front() < t - 3000) {
q.pop();
}
return q.size();
}
};
#endif //CPP_0933_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0680-Valid-Palindrome-II/cpp_0680/Solution2.h | //
// Created by ooooo on 2020/1/28.
//
#ifndef CPP_0680__SOLUTION2_H_
#define CPP_0680__SOLUTION2_H_
#include <iostream>
using namespace std;
/**
* 递归
*/
class Solution {
public:
bool validPalindrome(string s, int left, int right, bool deleted) {
if (left >= right) return true;
if (s[left] == s[right]) {
return validPalindrome(s, left + 1, right - 1, deleted);
}
if (deleted) return false;
return validPalindrome(s, left + 1, right, true) || validPalindrome(s, left, right - 1, true);
}
bool validPalindrome(string s) {
return validPalindrome(s, 0, s.size() - 1, false);
}
};
#endif //CPP_0680__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | lcof_014/cpp_014-1/Solution2.h | //
// Created by ooooo on 2020/3/11.
//
#ifndef CPP_014_1__SOLUTION2_H_
#define CPP_014_1__SOLUTION2_H_
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
/**
* dp[n] = max( dp[1] * dp[n-1], dp[2] * dp[n-2] )
*
* dp[n] 表示绳子长度为 n
*/
class Solution {
public:
int cuttingRope(int n) {
vector<int> dp(n + 1);
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
// 不为 n 时,可以取整段
dp[i] = i == n ? 1 : i;
for (int j = 1; j <= i / 2; ++j) {
dp[i] = max(dp[i], dp[j] * dp[i - j]);
}
}
return dp[n];
}
};
#endif //CPP_014_1__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0011-Container-With-Most-Water/cpp_0011/Solution1.h | //
// Created by ooooo on 2020/2/6.
//
#ifndef CPP_0011__SOLUTION1_H_
#define CPP_0011__SOLUTION1_H_
#include <iostream>
#include <vector>
/**
* 暴力破解
*/
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int ans = 0;
for (int i = 0; i < height.size(); ++i) {
for (int j = i + 1; j < height.size(); ++j) {
ans = max(ans, min(height[i], height[j])*(j - i));
}
}
return ans;
}
};
#endif //CPP_0011__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1688-Count of Matches in Tournament/cpp_1688/Solution1.h | /**
* @author ooooo
* @date 2020/12/15 20:21
*/
#ifndef CPP_1688__SOLUTION1_H_
#define CPP_1688__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
int numberOfMatches(int n) {
if (n == 1) return 0;
return n / 2 + numberOfMatches((n + 1) / 2);
}
};
#endif //CPP_1688__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0021-Merge-Two-Sorted-Lists/cpp_0021/ListNode.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/23.
//
#ifndef CPP_0021__LISTNODE_H_
#define CPP_0021__LISTNODE_H_
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif //CPP_0021__LISTNODE_H_
|
ooooo-youwillsee/leetcode | 0215-Kth-Largest-Element-in-an-Array/cpp_0215/Solution2.h | //
// Created by ooooo on 2020/2/20.
//
#ifndef CPP_0215__SOLUTION2_H_
#define CPP_0215__SOLUTION2_H_
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
/**
* heap
*/
class Solution {
public:
int findKthLargest(vector<int> &nums, int k) {
priority_queue<int, vector<int>, greater<int>> q;
for (auto &num: nums) {
if (q.size() < k) {
q.push(num);
} else {
if (q.top() < num) {
q.pop();
q.push(num);
}
}
}
return q.top();
}
};
#endif //CPP_0215__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0594-Longest-Harmonious-Subsequence/cpp_0594/Solution1.h | //
// Created by ooooo on 2020/1/12.
//
#ifndef CPP_0594__SOLUTION1_H_
#define CPP_0594__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/**
* 哈希表
*/
class Solution {
public:
int findLHS(vector<int> &nums) {
int ans = 0;
unordered_map<int, int> m;
for (const auto &num: nums) {
m[num]++;
}
// 不能在下面的for循环中使用m[k], 如果元素k不存在,就修改m.size()
for (const auto &entry: m) {
int c = 0;
if (m.count(entry.first - 1)) {
c = m[entry.first - 1];
}
if (m.count(entry.first + 1)) {
c = max(c, m[entry.first + 1]);
}
// c为0,表示没有差为1的元素
if (c == 0) continue;
ans = max(c + entry.second, ans);
}
return ans;
}
};
#endif //CPP_0594__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0045-Jump Game II/cpp_0045/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/6/4 20:16
*/
#ifndef CPP_0045__SOLUTION1_H_
#define CPP_0045__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* 暴力dp
*/
class Solution {
public:
int jump(vector<int> &nums) {
int n = (int) nums.size();
vector<int> dp(n, n);
dp[0] = 0;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (i - j <= nums[j]) {
dp[i] = min(dp[i], dp[j] + 1);
}
}
}
return dp[n - 1];
}
};
#endif //CPP_0045__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0290-Word-Pattern/cpp_0290/Solution1.h | //
// Created by ooooo on 2020/1/9.
//
#ifndef CPP_0290_SOLUTION1_H
#define CPP_0290_SOLUTION1_H
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> split2(string s, string sep) {
vector<string> res;
int i = 0;
s += sep;
int j = s.find_first_of(sep, i);
while (j != -1) {
res.push_back(s.substr(i, j - i));
i = j + 1;
j = s.find_first_of(sep, j + 1);
}
return res;
}
vector<string> split(string s, string sep) {
s += sep;
int i = s.find(sep);
vector<string> res;
int j = 0;
while (i != -1) {
res.push_back(s.substr(j, i - j));
j = i + 1;
i = s.find(sep, i + 1);
}
return res;
}
bool wordPattern(string pattern, string str) {
vector<string> strs = split(str, " ");
if (strs.size() != pattern.size()) return false;
unordered_map<char, string> m1;
unordered_map<string, char> m2;
for (int i = 0; i < pattern.size(); ++i) {
if (m1.count(pattern[i]) && m1[pattern[i]] != strs[i]) return false;
else {
if (m2.count(strs[i]) && m2[strs[i]] != pattern[i]) return false;
m1[pattern[i]] = strs[i];
m2[strs[i]] = pattern[i];
}
}
return true;
}
};
#endif //CPP_0290_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0061-Rotate List/cpp_0061/Solution1.h | /**
* @author ooooo
* @date 2020/10/5 18:03
*/
#ifndef CPP_0061__SOLUTION1_H_
#define CPP_0061__SOLUTION1_H_
#include "ListNode.h"
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == nullptr || k == 0) return head;
int len = 0;
ListNode * cur = head;
while (cur) {
cur = cur->next;
len++;
}
k %= len;
if (k == 0) return head;
cur = head;
int cnt = len - k;
while (cur && cnt) {
cnt--;
cur = cur->next;
}
ListNode *new_head = cur->next, *prev = new_head;
cur->next = nullptr;
while (prev->next) {
prev = prev->next;
}
prev->next = head;
return new_head;
}
};
#endif //CPP_0061__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0283-Move-Zeroes/cpp_0283/Solution2.h | <filename>0283-Move-Zeroes/cpp_0283/Solution2.h
//
// Created by ooooo on 2020/1/6.
//
#ifndef CPP_0283_SOLUTION2_H
#define CPP_0283_SOLUTION2_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int> &nums) {
if (nums.size() <= 1) return;
int count = 0, j = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != 0) {
nums[j++] = nums[i];
} else {
count++;
}
}
for (int k = nums.size() - 1; count--; --k) {
nums[k] = 0;
}
}
};
#endif //CPP_0283_SOLUTION2_H
|
ooooo-youwillsee/leetcode | lcof_016/cpp_016/Solution3.h | //
// Created by ooooo on 2020/3/12.
//
#ifndef CPP_016__SOLUTION3_H_
#define CPP_016__SOLUTION3_H_
#include <iostream>
using namespace std;
/**
* o(logN)
*/
class Solution {
public:
double myPow(double x, int n) {
if (x == 0) return 0;
double ans = 1.0;
long b = n;
if (b < 0) {
x = 1 / x;
b = -b;
}
while (b) {
if (b & 1) ans *= x;
x *= x;
b >>= 1;
}
return ans;
}
};
#endif //CPP_016__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0653-Two-Sum-IV-Input-is-a-BST/cpp_0653/Solution1.h | //
// Created by ooooo on 2020/1/3.
//
#ifndef CPP_0653_SOLUTION1_H
#define CPP_0653_SOLUTION1_H
#include "TreeNode.h"
#include <unordered_set>
class Solution {
public:
bool dfs(TreeNode *node, unordered_set<int> &s, int k) {
if (!node) return false;
if (s.count(k - node->val)) return true;
s.insert(node->val);
return dfs(node->left, s, k) || dfs(node->right, s, k);
}
bool findTarget(TreeNode *root, int k) {
unordered_set<int> s;
return dfs(root, s, k);
}
};
#endif //CPP_0653_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0075-Sort-Colors/cpp_0075/Solution1.h | //
// Created by ooooo on 2020/2/14.
//
#ifndef CPP_0075__SOLUTION1_H_
#define CPP_0075__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* 计数
*/
class Solution {
public:
void fill(vector<int> &nums, int start, int v, int count) {
for (int i = start, c = 0; c < count; ++i, c++) {
nums[i] = v;
}
}
void sortColors(vector<int> &nums) {
int count_0 = 0, count_1 = 0, count_2 = 0;
for (auto &num: nums) {
if (num == 0) count_0++;
else if (num == 1) count_1++;
else count_2++;
}
fill(nums, 0, 0, count_0);
fill(nums, count_0, 1, count_1);
fill(nums, count_0 + count_1, 2, count_2);
}
};
#endif //CPP_0075__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0560-Subarray Sum Equals K/cpp_0560/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 6/2/2021.
//
#ifndef CPP_0560_SOLUTION1_H
#define CPP_0560_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> m;
m[0] = 1;
int ans = 0;
int sum = 0;
for (int num : nums) {
sum += num;
if (m.find(sum - k) != m.end()) {
ans += m[sum - k];
}
m[sum]++;
}
return ans;
}
};
#endif //CPP_0560_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_032-3/cpp_032-3/Solution2.h | <reponame>ooooo-youwillsee/leetcode<gh_stars>10-100
//
// Created by ooooo on 2020/3/21.
//
#ifndef CPP_032_3__SOLUTION2_H_
#define CPP_032_3__SOLUTION2_H_
#include "TreeNode.h"
#include <queue>
/**
* dfs
*/
class Solution {
public:
void dfs(TreeNode *root, int level) {
if (!root) return;
if (ans.size() <= level) {
ans.push_back({});
}
ans[level].emplace_back(root->val);
level += 1;
dfs(root->left, level);
dfs(root->right, level);
}
vector<vector<int>> ans;
vector<vector<int>> levelOrder(TreeNode *root) {
dfs(root, 0);
for (int i = 0, len = ans.size(); i < len; ++i) {
if ((i & 1) == 1) reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
};
#endif //CPP_032_3__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0788-Rotated-Digits/cpp_0788/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/30.
//
#ifndef CPP_0788__SOLUTION1_H_
#define CPP_0788__SOLUTION1_H_
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
unordered_map<int, int> map = {
{0, 0}, {1, 1}, {8, 8},
{2, 5}, {5, 2}, {6, 9}, {9, 6},
{3, -1}, {4, -1}, {7, -1}
};
bool valid(int v) {
int sum = 0, num = v;
int count = 0;
while (v) {
int mod = v % 10;
if (map[mod] == -1) return false;
sum += pow(10, count) * map[mod];
v /= 10;
count++;
}
return sum != num;
}
int rotatedDigits(int N) {
int ans = 0;
for (int i = 1; i <= N; ++i) {
if (valid(i)) ans++;
}
return ans;
}
};
#endif //CPP_0788__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0263-Ugly-Number/cpp_0263/Solution1.h | /**
* @author ooooo
* @date 2021/4/10 09:56
*/
#ifndef CPP_0263__SOLUTION1_H_
#define CPP_0263__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool isUgly(int n) {
if (n == 1) return true;
while (n > 1) {
if (n % 2 == 0) {
n /= 2;
} else if (n % 3 == 0) {
n /= 3;
} else if (n % 5 == 0) {
n /= 5;
} else {
return false;
}
}
return n == 1;
}
};
#endif //CPP_0263__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0111-Minimum-Depth-of-Binary-Tree/cpp_0111/Solution1.h | //
// Created by ooooo on 2019/11/4.
//
#ifndef CPP_0111_SOLUTION1_H
#define CPP_0111_SOLUTION1_H
#include "TreeNode.h"
class Solution {
private:
int min = 0;
void dfs(int level, TreeNode *node) {
if (!node) return;
if (!node->left && !node->right) {
if (min == 0) {
// min为0,表明第一次
min = level;
} else if (level < min) {
min = level;
}
}
dfs(level + 1, node->left);
dfs(level + 1, node->right);
}
public:
int minDepth(TreeNode *root) {
dfs(1, root);
return this->min;
}
};
#endif //CPP_0111_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0434-Number of-Segments-in-a-String/cpp_0434/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/25.
//
#ifndef CPP_0434__SOLUTION1_H_
#define CPP_0434__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
int countSegments(string s) {
s += " ";
int ans = 0, i = 0, j = s.find_first_of(" ", i);
while (j != -1) {
string word = s.substr(i, j - i);
if (word != "") {
ans++;
}
i = j + 1;
j = s.find_first_of(" ", i);
}
return ans;
}
};
#endif //CPP_0434__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0147-Insertion Sort List/cpp_0147/ListNode.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2020/11/20 09:10
*/
#ifndef CPP_0147__LISTNODE_H_
#define CPP_0147__LISTNODE_H_
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif //CPP_0147__LISTNODE_H_
|
ooooo-youwillsee/leetcode | 1800-Maximum Ascending Subarray Sum/cpp_1800/Solution1.h | /**
* @author ooooo
* @date 2021/3/28 12:17
*/
#ifndef CPP_1800__SOLUTION1_H_
#define CPP_1800__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <stack>
#include <numeric>
#include <queue>
using namespace std;
class Solution {
public:
int maxAscendingSum(vector<int> &nums) {
int ans = nums[0];
int cur = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > nums[i - 1]) {
cur += nums[i];
} else {
ans = max(ans, cur);
cur = nums[i];
ans = max(ans, cur);
}
}
ans = max(ans, cur);
return ans;
}
};
#endif //CPP_1800__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0532-K-diff-Pairs-in-an-Array/cpp_0532/Solution1.h | //
// Created by ooooo on 2020/1/8.
//
#ifndef CPP_0532_SOLUTION1_H
#define CPP_0532_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/**
* 暴力 超时
*/
class Solution {
public:
int findPairs(vector<int> &nums, int k) {
if (nums.empty()) return 0;
unordered_set<string> ans;
for (int i = 0; i < nums.size() - 1; ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
int max, min;
if (nums[i] > nums[j]) {
max = nums[i];
min = nums[j];
} else {
max = nums[j];
min = nums[i];
}
if (max - min == k) ans.insert(to_string(min) + "#" + to_string(max));
}
}
return ans.size();
}
};
#endif //CPP_0532_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0127-Word-Ladder/cpp_0127/Solution3.h | <gh_stars>10-100
//
// Created by ooooo on 2019/12/31.
//
#ifndef CPP_0127_SOLUTION3_H
#define CPP_0127_SOLUTION3_H
#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
unordered_set<string> set(wordList.begin(), wordList.end());
unordered_set<string> visited;
queue<string> q;
visited.insert(beginWord);
q.push(beginWord);
int depth = 1;
while (!q.empty()) {
int size = q.size();
depth += 1;
while (size--) {
string word = q.front();
q.pop();
for (int i = 0; i < word.size(); ++i) {
string s = word;
for (int j = 'a'; j < 'z'; ++j) {
s[i] = j;
if (!set.count(s) || visited.count(s)) continue;
if (s == endWord) return depth;
q.push(s);
visited.insert(s);
}
}
}
}
return 0;
}
};
#endif //CPP_0127_SOLUTION3_H
|
ooooo-youwillsee/leetcode | 1018-Binary Prefix Divisible By 5/cpp_1018/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/1/14 09:04
*/
#ifndef CPP_1018__SOLUTION1_H_
#define CPP_1018__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
// 101 -> 5
// 1010 -> 10
// 1111 -> 8 + 4 + 2 + 1 = 15
// 10100 -> 8 + 4 + 2 + 1 = 20
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int> &A) {
int i = 0;
vector<bool> ans;
for (int j = 0; j < A.size(); ++j) {
i = ((i << 1) + A[j]) % 5;
ans.push_back(i == 0);
}
return ans;
}
};
#endif //CPP_1018__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0189-Rotate-Array/cpp_0189/Solution1.h | <filename>0189-Rotate-Array/cpp_0189/Solution1.h
//
// Created by ooooo on 2019/12/5.
//
#ifndef CPP_0189_SOLUTION1_H
#define CPP_0189_SOLUTION1_H
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// 每次移动一个, 总共k次
void rotate(vector<int> &nums, int k) {
if (nums.size() == 0) return;
k %= nums.size();
for (int i = 0; i < k; i++) {
int temp = nums[nums.size() - 1];
for (int j = nums.size() - 1; j > 0; --j) {
nums[j] = nums[j - 1];
}
nums[0] = temp;
}
}
};
#endif //CPP_0189_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0085-Maximal Rectangle/cpp_0085/Solution1.h | <reponame>ooooo-youwillsee/leetcode<gh_stars>10-100
/**
* @author ooooo
* @date 2020/12/26 11:24
*/
#ifndef CPP_0085__SOLUTION1_H_
#define CPP_0085__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maximalRectangle(vector<vector<char>> &matrix) {
if (matrix.empty()) return 0;
// 先计算每个点左边的宽度
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> width(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (j == 0) {
width[i][j] = matrix[i][j] == '1';
continue;
}
if (matrix[i][j] == '1') {
width[i][j] = width[i][j - 1] + 1;
}
}
}
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '0') {
continue;
}
// 向上计算最小宽度
int min_width = INT_MAX;
for (int k = i; k >= 0; --k) {
min_width = min(min_width, width[k][j]);
ans = max(ans, min_width * (i - k + 1));
}
}
}
return ans;
}
};
#endif //CPP_0085__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0061-Rotate List/cpp_0061/Solution2.h | /**
* @author ooooo
* @date 2020/10/5 20:07
*/
#ifndef CPP_0061__SOLUTION2_H_
#define CPP_0061__SOLUTION2_H_
#include "ListNode.h"
/**
* 先首尾相连
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == nullptr || k == 0) return head;
int len = 1;
ListNode *cur = head;
while (cur->next) {
cur = cur->next;
len++;
}
k %= len;
if (k == 0) return head;
cur->next = head;
cur = head;
int cnt = len - k - 1;
while (cnt) {
cnt--;
cur = cur->next;
}
ListNode *new_head = cur->next;
cur->next = nullptr;
return new_head;
}
};
#endif //CPP_0061__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0257-Binary-Tree-Paths/cpp_0257/Solution1.h | <filename>0257-Binary-Tree-Paths/cpp_0257/Solution1.h
//
// Created by ooooo on 2020/1/2.
//
#ifndef CPP_0257_SOLUTION1_H
#define CPP_0257_SOLUTION1_H
#include <vector>
#include <queue>
#include <unordered_map>
#include "TreeNode.h"
class Solution {
public:
vector<string> binaryTreePaths2(TreeNode *root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
queue<TreeNode *> q;
queue<TreeNode *> prev;
unordered_map<TreeNode *, string> paths;
vector<string> res;
q.push(root);
prev.push(root);
paths[root] = to_string(root->val);
while (!q.empty()) {
TreeNode *node = q.front();
TreeNode *parent = prev.front();
q.pop();
prev.pop();
if (node != root) {
if (!node->left && !node->right) {
res.push_back(paths[parent] + "->" + to_string(node->val));
continue;
}
paths[node] = paths[parent] + "->" + to_string(node->val);
}
if (node->left) {
q.push(node->left);
prev.push(node);
}
if (node->right) {
q.push(node->right);
prev.push(node);
}
}
return res;
}
vector<string> binaryTreePaths(TreeNode *root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
queue<TreeNode *> q;
queue<string> paths;
vector<string> res;
q.push(root);
paths.push(to_string(root->val));
while (!q.empty()) {
TreeNode *node = q.front();
string parentPath = paths.front();
q.pop();
paths.pop();
if (node != root) {
if (!node->left && !node->right) {
res.push_back(parentPath + "->" + to_string(node->val));
continue;
}
parentPath += "->" + to_string(node->val);
}
if (node->left) {
q.push(node->left);
paths.push(parentPath);
}
if (node->right) {
q.push(node->right);
paths.push(parentPath);
}
}
return res;
}
};
#endif //CPP_0257_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_063/cpp_063/Solution1.h | //
// Created by ooooo on 2020/4/24.
//
#ifndef CPP_063__SOLUTION1_H_
#define CPP_063__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(2, vector<int>(2, 0)));
dp[0][1][0] = INT_MIN;
dp[0][1][1] = INT_MIN;
dp[0][0][1] = INT_MIN;
int ans = 0;
for (int i = 0; i < n; ++i) {
int p = prices[i];
dp[i + 1][0][0] = dp[i][0][0];
dp[i + 1][1][0] = INT_MIN;
dp[i + 1][1][1] = max(dp[i][1][1], dp[i][0][0] - p);
dp[i + 1][0][1] = max(dp[i][0][1], dp[i][1][1] + p);
ans = max(ans, dp[i + 1][0][1]);
}
return ans;
}
};
#endif //CPP_063__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0876-Middle-of-the-Linked-List/cpp_0876/Solution2.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/23.
//
#ifndef CPP_0876__SOLUTION2_H_
#define CPP_0876__SOLUTION2_H_
#include "ListNode.h"
#include <vector>
/**
* 遍历数组存放
*/
class Solution {
public:
ListNode *middleNode(ListNode *head) {
vector<ListNode *> ans;
while (head) {
ans.push_back(head);
head = head->next;
}
int size = ans.size();
return size % 2 == 0 ? ans[size / 2 + 1] : ans[size / 2];
}
};
#endif //CPP_0876__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | lcof_016/cpp_016/Solution2.h | //
// Created by ooooo on 2020/3/12.
//
#ifndef CPP_016__SOLUTION2_H_
#define CPP_016__SOLUTION2_H_
#include <iostream>
using namespace std;
/**
* o(logN)
*/
class Solution {
public:
double help(double x, long n) {
if (n == 1) return x;
return n & 1 ? x * help(x * x, n / 2) : help(x * x, n / 2);
}
double myPow(double x, int n) {
if (x == 0) return 0;
if (n == 0) return 1;
return n < 0 ? 1.0 / help(x, (long) n * -1.0) : help(x, (long) n);
}
};
#endif //CPP_016__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | lcof_027/cpp_027/Solution1.h | //
// Created by ooooo on 2020/3/17.
//
#ifndef CPP_027__SOLUTION1_H_
#define CPP_027__SOLUTION1_H_
#include "TreeNode.h"
class Solution {
public:
TreeNode *mirrorTree(TreeNode *root) {
if (!root)return root;
TreeNode *left = mirrorTree(root->left);
TreeNode *right = mirrorTree(root->right);
root->right = left;
root->left = right;
return root;
}
};
#endif //CPP_027__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0551-Student-Attendance-Record-I/cpp_0551/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/28.
//
#ifndef CPP_0551__SOLUTION1_H_
#define CPP_0551__SOLUTION1_H_
#include <iostream>
using namespace std;
class Solution {
public:
bool checkRecord(string s) {
int A_count = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == 'A') A_count++;
if (A_count > 1) return false;
if (i > s.size() - 3) continue;
if (s[i] == s[i + 1] && s[i + 1] == s[i + 2] && s[i + 2] == 'L') return false;
}
return true;
}
};
#endif //CPP_0551__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1312-Minimum Insertion Steps to Make a String Palindrome/cpp_1312/Solution1.h | /**
* @author ooooo
* @date 2020/10/4 21:18
*/
#ifndef CPP_1312__SOLUTION1_H_
#define CPP_1312__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minInsertions(string s) {
int n = s.size();
vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1];
} else {
dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1;
}
}
}
return dp[0][n - 1];
}
};
#endif //CPP_1312__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_011/cpp_011/Solution2.h | <gh_stars>10-100
//
// Created by ooooo on 2020/3/9.
//
#ifndef CPP_011__SOLUTION2_H_
#define CPP_011__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* O( log(n) )
*/
class Solution {
public:
int line_find(vector<int> &numbers, int l, int r) {
int ans = INT_MAX;
for (int i = l; i < r; i++) {
if (ans > numbers[i]) ans = numbers[i];
}
return ans;
}
int minArray(vector<int> &numbers) {
int l = 0, r = numbers.size() - 1;
if (numbers[l] < numbers[r]) return numbers[0];
while (l < r - 1) {
int mid = l + (r - l) / 2;
// 10, 10, 1, 10, 这种情况线性查找
if (numbers[mid] == numbers[l] && numbers[mid] == numbers[r]) {
return line_find(numbers, l, r);
}
if (numbers[mid] <= numbers[r]) {
r = mid;
} else if (numbers[mid] >= numbers[l]) {
l = mid;
}
}
return numbers[r];
}
};
#endif //CPP_011__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0141-Linked-List-Cycle/cpp_0141/ListNode.h | <gh_stars>10-100
//
// Created by ooooo on 2019/10/30.
//
#ifndef CPP_0141_LISTNODE_H
#define CPP_0141_LISTNODE_H
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif //CPP_0141_LISTNODE_H
|
ooooo-youwillsee/leetcode | 1309-Decrypt-String-from-Alphabet-to-Integer-Mapping/cpp_1309/Solution1.h | //
// Created by ooooo on 2020/2/3.
//
#ifndef CPP_1309__SOLUTION1_H_
#define CPP_1309__SOLUTION1_H_
#include <iostream>
#include <unordered_map>
#include <sstream>
using namespace std;
class Solution {
public:
string freqAlphabets(string s) {
unordered_map<string, char> m;
for (int i = 1; i <= 26; ++i) {
if (i < 10) {
m[to_string(i)] = 'a' + i - 1;
} else {
m[to_string(i) + "#"] = 'a' + i - 1;
}
}
stringstream ss;
for (int i = 0; i < s.size();) {
if (i + 2 < s.size() && s[i + 2] == '#') {
ss << m[s.substr(i, 3)];
i += 3;
} else {
ss << m[s.substr(i, 1)];
i += 1;
}
}
return ss.str();
}
};
#endif //CPP_1309__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0993-Cousins-in-Binary-Tree/cpp_0993/Solution2.h | //
// Created by ooooo on 2020/1/5.
//
#ifndef CPP_0993_SOLUTION2_H
#define CPP_0993_SOLUTION2_H
#include "TreeNode.h"
class Solution {
public:
int xDepth = 0, yDepth = 0;
TreeNode *xParent = nullptr, *yParent = nullptr;
int x, y;
void dfs(TreeNode *node, int depth, TreeNode *parent) {
if (!node) return;
if (node->val == x) {
xParent = parent;
xDepth = depth;
}
if (node->val == y) {
yParent = parent;
yDepth = depth;
}
depth += 1;
dfs(node->left, depth, node);
dfs(node->right, depth, node);
}
bool isCousins(TreeNode *root, int x, int y) {
if (!root) return false;
this->x = x;
this->y = y;
dfs(root, 0, nullptr);
return xDepth == yDepth && xParent != yParent;
}
};
#endif //CPP_0993_SOLUTION2_H
|
ooooo-youwillsee/leetcode | 1647-Minimum Deletions to Make Character Frequencies Unique/cpp_1647/Solution1.h | /**
* @author ooooo
* @date 2021/2/28 13:04
*/
#ifndef CPP_1647__SOLUTION1_H_
#define CPP_1647__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <stack>
#include <numeric>
using namespace std;
class Solution {
public:
int minDeletions(string s) {
unordered_map<int, int> map;
int max_count = 0;
for (auto &c: s) {
map[c]++;
max_count = max(max_count, map[c]);
}
vector<bool> flag(max_count + 1, false);
int ans = 0;
for (auto[k, v] : map) {
if (!flag[v]) {
flag[v] = true;
} else {
for (int i = v; i > 0; --i) {
if (!flag[i]) {
flag[i] = true;
break;
}
ans++;
}
}
}
return ans;
}
};
#endif //CPP_1647__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0392-Is-Subsequence/cpp_0392/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/18.
//
#ifndef CPP_0392__SOLUTION1_H_
#define CPP_0392__SOLUTION1_H_
#include <iostream>
using namespace std;
/**
* 暴力破解 double loop
*/
class Solution {
public:
bool isSubsequence(string s, string t) {
int ans = 0, i = 0;
for (auto &c: s) {
while (i < t.size()) {
if (t[i++] == c) {
ans++;
break;
}
}
}
return ans == s.size();
}
};
#endif //CPP_0392__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp_1237/Solution2.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/22.
//
#ifndef CPP_1237__SOLUTION2_H_
#define CPP_1237__SOLUTION2_H_
#include "CustomFunction.h"
/**
* binary search
*/
class Solution {
public:
vector<vector<int>> findSolution(CustomFunction &customfunction, int z) {
vector<vector<int>> ans;
for (int x = 1; x <= 1000; ++x) {
int left = 1, right = 1000;
while (left <= right) {
int mid = left + (right - left) / 2;
if (customfunction.f(x, mid) < z) {
left = mid + 1;
} else if (customfunction.f(x, mid) > z) {
right = mid - 1;
} else {
ans.push_back({x, mid});
break;
}
}
}
return ans;
}
};
#endif //CPP_1237__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0700-Search-in-a-Binary-Search-Tree/cpp_0700/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/1/5.
//
#ifndef CPP_0700_SOLUTION1_H
#define CPP_0700_SOLUTION1_H
#include "TreeNode.h"
class Solution {
public:
TreeNode *searchBST(TreeNode *root, int val) {
if (!root) return nullptr;
if (root->val < val) {
return searchBST(root->right, val);
} else if (root->val > val) {
return searchBST(root->left, val);
}
return root;
}
};
#endif //CPP_0700_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 1700-Number of Students Unable to Eat Lunch/cpp_1700/Solution1.h | <reponame>ooooo-youwillsee/leetcode<filename>1700-Number of Students Unable to Eat Lunch/cpp_1700/Solution1.h
/**
* @author ooooo
* @date 2021/1/24 18:07
*/
#ifndef CPP_1700__SOLUTION1_H_
#define CPP_1700__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
class Solution2 {
int countStudents(vector<int> &students, vector<int> &sandwiches) {
deque<int> q(students.begin(), students.end());
int i = 0, cnt = students.size(), prev_i = 0;
while (!q.empty()) {
auto stu = q.front();
q.pop_front();
if (stu == sandwiches[i]) {
prev_i = i;
i++;
} else {
q.push_back(stu);
}
cnt--;
if (cnt < 0) {
if (prev_i == i) {
break;
}
prev_i = i;
cnt = students.size();
}
}
return q.size();
}
};
#endif //CPP_1700__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0720-Longest-Word-in-Dictionary/cpp_0720/Solution3.h | <reponame>ooooo-youwillsee/leetcode<gh_stars>10-100
//
// Created by ooooo on 2020/1/14.
//
#ifndef CPP_0720__SOLUTION3_H_
#define CPP_0720__SOLUTION3_H_
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/**
* Trie
*/
class Solution {
private:
struct Node {
char c;
bool isWord;
vector<Node *> children;
Node(char c) : c(c), children(vector<Node *>(26, nullptr)) {
isWord = false;
}
void insert(string s) {
Node *curNode = this;
for (const auto &item: s) {
int index = item - 'a';
if (!curNode->children[index]) {
curNode->children[index] = new Node(item);
}
curNode = curNode->children[index];
}
curNode->isWord = true;
}
bool check(string s) {
Node *curNode = this;
for (const auto &item: s) {
int index = item - 'a';
Node *node = curNode->children[index];
if (!node || !node->isWord) return false;
curNode = node;
}
return true;
}
};
public:
string longestWord(vector<string> &words) {
Node *root = new Node(0);
for (const auto &word: words) {
root->insert(word);
}
string ans = "";
for (const auto &word: words) {
if (root->check(word) && (ans.size() < word.size() || (ans.size() == word.size() && word < ans))) {
ans = word;
}
}
return ans;
}
};
#endif //CPP_0720__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0501-Find-Mode-in-Binary-Search-Tree/cpp_0501/Solution1.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/2.
//
#ifndef CPP_0501_SOLUTION1_H
#define CPP_0501_SOLUTION1_H
#include "TreeNode.h"
#include <vector>
#include <unordered_map>
class Solution {
public:
void dfs(TreeNode *node, unordered_map<int, int> &map, int &maxCount) {
if (!node) return;
if (map.count(node->val)) {
map[node->val] += 1;
} else {
map[node->val] = 1;
}
maxCount = maxCount > map[node->val] ? maxCount : map[node->val];
dfs(node->left, map, maxCount);
dfs(node->right, map, maxCount);
}
vector<int> findMode(TreeNode *root) {
unordered_map<int, int> map;
int maxCount = 0;
dfs(root, map, maxCount);
vector<int> res;
for (auto entry: map) {
if (entry.second == maxCount) {
res.push_back(entry.first);
}
}
return res;
}
};
#endif //CPP_0501_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_055-1/cpp_055-1/Solution1.h | //
// Created by ooooo on 2020/4/11.
//
#ifndef CPP_055_1__SOLUTION1_H_
#define CPP_055_1__SOLUTION1_H_
#include "TreeNode.h"
#include <queue>
/**
* bfs
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if (!root) return 0;
queue<TreeNode *> q;
q.push(root);
int level = 0;
while (!q.empty()) {
level++;
for (int i = 0, len = q.size(); i < len; ++i) {
auto node = q.front();
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return level;
}
};
#endif //CPP_055_1__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0257-Binary-Tree-Paths/cpp_0257/Solution2.h | <gh_stars>10-100
//
// Created by ooooo on 2020/1/2.
//
#ifndef CPP_0257_SOLUTION2_H
#define CPP_0257_SOLUTION2_H
#include "TreeNode.h"
#include <vector>
class Solution {
public:
void help(TreeNode *node, string s, vector<string> &res) {
if (s == "") {
s = to_string(node->val);
} else {
s += "->" + to_string(node->val);
}
if (!node->left && !node->right) {
res.push_back(s);
return;
}
if (node->left)
help(node->left, s, res);
if (node->right)
help(node->right, s, res);
}
vector<string> binaryTreePaths(TreeNode *root) {
if (!root) return {};
vector<string> res;
help(root, "", res);
return res;
}
};
#endif //CPP_0257_SOLUTION2_H
|
ooooo-youwillsee/leetcode | lcof_035/cpp_035/Solution2.h | <reponame>ooooo-youwillsee/leetcode<filename>lcof_035/cpp_035/Solution2.h
//
// Created by ooooo on 2020/3/22.
//
#ifndef CPP_035__SOLUTION2_H_
#define CPP_035__SOLUTION2_H_
#include "Node.h"
#include <unordered_map>
/**
* dfs
*/
class Solution {
public:
Node *copy(Node *node) {
if (!node) return nullptr;
if (node_map.count(node)) return node_map[node];
Node *new_node = new Node(node->val);
node_map[node] = new_node;
new_node->next = copy(node->next);
new_node->random = copy(node->random);
return new_node;
}
unordered_map<Node *, Node *> node_map;
Node *copyRandomList(Node *head) {
return copy(head);
}
};
#endif //CPP_035__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0697-Degree of an Array/cpp_0697/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/2/20 09:36
*/
#ifndef CPP_0697__SOLUTION1_H_
#define CPP_0697__SOLUTION1_H_
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
int findShortestSubArray(vector<int> &nums) {
// count, start, end
vector<vector<int>> m(50001, {0, -1, -1});
int count = 0;
vector<int> maxNums;
for (int i = 0; i < nums.size(); ++i) {
int num = nums[i];
m[num][0] +=1;
if (m[num][1] == -1) {
m[num][1] = m[num][2] = i;
}
if (m[num][0] > count) {
count = m[num][0];
maxNums.clear();
maxNums.push_back(num);
m[num][2] = i;
} else if (m[num][0] == count) {
maxNums.push_back(num);
m[num][2] = i;
}
}
int ans = nums.size();
for (int i = 0; i < maxNums.size(); ++i) {
ans = min(ans, m[maxNums[i]][2] - m[maxNums[i]][1]);
}
return ans;
}
};
#endif //CPP_0697__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0206-Reverse-Linked-List/cpp_0206/Solution1.h | <filename>0206-Reverse-Linked-List/cpp_0206/Solution1.h
//
// Created by ooooo on 2019/10/29.
//
#ifndef CPP_0206_SOLUTION1_H
#define CPP_0206_SOLUTION1_H
#include <iostream>
#include "ListNode.h"
using namespace std;
class Solution1 {
private:
public:
ListNode *reverseList(ListNode *head) {
ListNode *prev = NULL;
while (head) {
ListNode *nextNode = head->next;
head->next = prev;
prev = head;
head = nextNode;
}
return prev;
}
};
#endif //CPP_0206_SOLUTION1_H
|
ooooo-youwillsee/leetcode | lcof_043/cpp_043/Solution2.h | <filename>lcof_043/cpp_043/Solution2.h
//
// Created by ooooo on 2020/3/28.
//
#ifndef CPP_043__SOLUTION2_H_
#define CPP_043__SOLUTION2_H_
#include <iostream>
#include <math.h>
using namespace std;
class Solution {
public:
int dfs(int n) {
if (n <= 0) return 0;
string s = to_string(n);
int high = s[0] - '0';
int pow = powl(10, s.length() - 1);
int last = n - high * pow;
if (high == 1) {
return dfs(pow - 1) + dfs(last) + last + 1;
} else {
return pow + high * dfs(pow - 1) + dfs(last);
}
}
int countDigitOne(int n) {
return dfs(n);
}
};
#endif //CPP_043__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | lcof_049/cpp_049/Solution2.h | //
// Created by ooooo on 2020/4/6.
//
#ifndef CPP_049__SOLUTION2_H_
#define CPP_049__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* 把已经排好序的丑数 分别 *2,*3,*5,取最小的数,添加进数组中
*/
class Solution {
public:
int findMinValue(int count, vector<int> &nums, int num) {
for (int i = 0; i < count; ++i) {
if (nums[i] * num > nums[count - 1]) return nums[i] * num;
}
return -1;
}
int nthUglyNumber(int n) {
vector<int> nums(n, 1);
int count = 1;
while (count < n) {
int min_v = min({
findMinValue(count, nums, 2),
findMinValue(count, nums, 3),
findMinValue(count, nums, 5)});
nums[count++] = min_v;
}
return nums[n - 1];
}
};
#endif //CPP_049__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0031-Next-Permutation/cpp_0031/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/2/8.
//
#ifndef CPP_0031__SOLUTION1_H_
#define CPP_0031__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int> &nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
if (i >= 0) {
int j = nums.size() - 1;
while (j >= 0 && nums[j] <= nums[i]) j--;
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}
};
#endif //CPP_0031__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_026/cpp_026/TreeNode.h | <filename>lcof_026/cpp_026/TreeNode.h
//
// Created by ooooo on 2020/3/17.
//
#ifndef CPP_026__TREENODE_H_
#define CPP_026__TREENODE_H_
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(vector<int> nums) : TreeNode(nums[0]) {
queue<TreeNode *> q;
q.push(this);
for (int i = 1, len = nums.size(); i < len;) {
TreeNode *p = q.front();
q.pop();
if (nums[i] != INT_MAX) {
p->left = new TreeNode(nums[i]);
}
if (i + 1 == len) return;
if (nums[i + 1] != INT_MAX) {
p->right = new TreeNode(nums[i + 1]);
}
i += 2;
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
}
};
#endif //CPP_026__TREENODE_H_
|
ooooo-youwillsee/leetcode | 1641-Count Sorted Vowel Strings/cpp_1641/Solution1.h | <filename>1641-Count Sorted Vowel Strings/cpp_1641/Solution1.h
/**
* @author ooooo
* @date 2020/11/15 09:35
*/
#ifndef CPP_1641__SOLUTION1_H_
#define CPP_1641__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <set>
#include <map>
#include <numeric>
#include <stack>
#include <queue>
using namespace std;
class Solution {
public:
int countVowelStrings(int n) {
vector<int> nums = {1, 1, 1, 1, 1};
while (n > 1) {
for (int i = nums.size() - 2; i >= 0; i--) {
nums[i] += nums[i + 1];
}
n--;
}
return accumulate(nums.begin(), nums.end(), 0);
}
};
#endif //CPP_1641__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0824-Goat-Latin/cpp_0824/SolutIon2.h | <reponame>ooooo-youwillsee/leetcode<filename>0824-Goat-Latin/cpp_0824/SolutIon2.h
//
// Created by ooooo on 2020/1/31.
//
#ifndef CPP_0824__SOLUTION2_H_
#define CPP_0824__SOLUTION2_H_
#include <iostream>
#include <sstream>
#include <unordered_set>
using namespace std;
/**
* 拼接字符串 使用stringstream
*/
class Solution {
public:
unordered_set<char> set = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
void help(stringstream &ss, string word, int count, bool space) {
if (set.count(word[0])) {
// 元音
ss << word;
} else {
ss << word.substr(1, word.size() - 1) << word.substr(0, 1);
}
ss << "ma";
ss << string(count, 'a');
if (space) {
ss << " ";
}
}
string toGoatLatin(string S) {
int i = 0, j = S.find(" ", i), count = 1;
stringstream ss;
while (j != -1) {
string word = S.substr(i, j - i);
help(ss, word, count++, true);
i = j + 1;
j = S.find(" ", i);
}
help(ss, S.substr(i, S.size() - i), count++, false);
return ss.str();
}
};
#endif //CPP_0824__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0019-Remove-Nth-Node-From-End-of-List/cpp_0019/Solution2.h | //
// Created by ooooo on 2020/2/8.
//
#ifndef CPP_0019__SOLUTION2_H_
#define CPP_0019__SOLUTION2_H_
#include "ListNode.h"
#include <vector>
/**
* 双指针, 其中一个先走n个,(如果有虚拟头指针,走n+1)
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *dummyNode = new ListNode(0), *cur = dummyNode, *prev = dummyNode;
dummyNode->next = head;
for (int i = 0; i < n + 1; ++i) {
cur = cur->next;
}
while (cur) {
cur = cur->next;
prev = prev->next;
}
prev->next = prev->next->next;
return dummyNode->next;
}
};
#endif //CPP_0019__SOLUTION2_H_
|
ooooo-youwillsee/leetcode | 0070-Climbing-Stairs/cpp_0070/Solution1.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2019/12/15.
//
#ifndef CPP_0070_SOLUTION1_H
#define CPP_0070_SOLUTION1_H
/**
* f(n) = f(n-1) + f(n-2)
*/
class Solution {
public:
int climbStairs(int n) {
if (n < 3)
return n;
int *res = new int[n + 1];
res[0] = 1;
res[1] = 1;
for (int i = 2; i <= n; ++i) {
res[i] = res[i - 1] + res[i - 2];
}
return res[n];
}
};
#endif //CPP_0070_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0024-Swap-Nodes-in-Pairs/cpp_0024/Solution1.h | //
// Created by ooooo on 2019/10/30.
//
#ifndef CPP_0024_SOLUTION1_H
#define CPP_0024_SOLUTION1_H
#include <iostream>
#include "ListNode.h"
using namespace std;
class Solution {
public:
/**
* 给定 1->2->3->4, 你应该返回 2->1->4->3.
* @param head
* @return
*/
ListNode *swapPairs(ListNode *head) {
ListNode *result = head;
ListNode *cur = head;
ListNode *prev = NULL;
while (cur && cur->next) {
ListNode *a = cur;
ListNode *b = cur->next;
if (!prev) {
result = b;
}
cur = b->next;
b->next = a;
prev = a;
prev->next = cur ? cur->next ? cur->next : cur : NULL;
}
return result;
}
};
#endif //CPP_0024_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0581-Shortest-Unsorted-Continuous-Subarray/cpp_0581/Solution1.h | //
// Created by ooooo on 2020/2/7.
//
#ifndef CPP_0581__SOLUTION1_H_
#define CPP_0581__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
*双指针
*/
class Solution {
public:
int findUnsortedSubarray(vector<int> &nums) {
int left = 0, right = nums.size() - 1;
bool find_left = false, find_right = false;
while (left <= right) {
for (int i = left + 1; i <= right; ++i) {
if (nums[i] < nums[left]) {
find_left = true;
break;
}
}
if (find_left) break;
left += 1;
}
while (left <= right) {
for (int i = right - 1; i >= left; --i) {
if (nums[i] > nums[right]) {
find_right = true;
break;
}
}
if (find_right) break;
right -= 1;
}
return right - left + 1;
}
};
#endif //CPP_0581__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_038/cpp_038/Solution1.h | //
// Created by ooooo on 2020/3/24.
//
#ifndef CPP_038__SOLUTION1_H_
#define CPP_038__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
void dfs(string &str) {
if (str.size() == s.size()) {
str_set.insert(str);
return;
}
for (int i = 0, len = s.size(); i < len; ++i) {
if (s[i] == '$') continue;
str.push_back(s[i]);
s[i] = '$';
dfs(str);
s[i] = str[str.size() - 1];
str.pop_back();
}
}
unordered_set<string> str_set;
string s;
vector<string> permutation(string s) {
this->s = s;
string str = "";
dfs(str);
vector<string> ans;
for (auto &item: str_set) ans.emplace_back(item);
return ans;
}
};
#endif //CPP_038__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcp-029/cpp_029/Solution1.h | <reponame>ooooo-youwillsee/leetcode
/**
* @author ooooo
* @date 2021/4/10 20:39
*/
#ifndef CPP_029__SOLUTION1_H_
#define CPP_029__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
typedef long long ll;
ll work(ll n, ll a, ll b) {
ll q = min(min(a, b), min(n - a + 1, n - b + 1));
ll ans;
if (a <= b) {
q--;
ans = 4 * (n - q) * q + a + b - 2 * (q + 1) + 1;
} else
ans = 4 * (n - q) * q - a - b + 2 * q + 1;
return ans % 9;
}
int orchestraLayout(int n, int x, int y) {
int ans = work(n, x + 1, y + 1);
// 没有0这个数字
return ans == 0 ? 9 : ans;
}
};
#endif //CPP_029__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0456-132 Pattern/cpp_0456/Solution1.h | <filename>0456-132 Pattern/cpp_0456/Solution1.h
/**
* @author ooooo
* @date 2021/3/24 16:32
*/
#ifndef CPP_0456__SOLUTION1_H_
#define CPP_0456__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <set>
using namespace std;
// o(nlogn)
class Solution {
public:
bool find132pattern(vector<int> &nums) {
int n = nums.size();
if (n < 3) {
return false;
}
int left_value = nums[0];
multiset<int> rights;
for (int i = 2; i < n; ++i) {
rights.insert(nums[i]);
}
for (int i = 1; i < n - 1; ++i) {
if (left_value < nums[i]) {
auto it = rights.upper_bound(left_value);
if (it != rights.end() && *it < nums[i]) {
return true;
}
}
left_value = min(left_value, nums[i]);
rights.erase(rights.find(nums[i + 1]));
}
return false;
}
};
#endif //CPP_0456__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | lcof_053-1/cpp_053-1/Solution3.h | <reponame>ooooo-youwillsee/leetcode
//
// Created by ooooo on 2020/4/9.
//
#ifndef CPP_053_1__SOLUTION3_H_
#define CPP_053_1__SOLUTION3_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int low_bound(vector<int> &nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
if (mid == 0) return mid;
if (nums[mid - 1] != target) return mid;
else r = mid - 1;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
int up_bound(vector<int> &nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
if (mid == nums.size() - 1) return mid;
if (nums[mid + 1] != target) return mid;
else l = mid + 1;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
int search(vector<int> &nums, int target) {
if (nums.empty()) return 0;
auto i = low_bound(nums, target);
if (i == -1) return 0;
return up_bound(nums, target) - i + 1;
}
};
#endif //CPP_053_1__SOLUTION3_H_
|
ooooo-youwillsee/leetcode | 0062-Unique-Paths/cpp_0062/Solution1.h | <filename>0062-Unique-Paths/cpp_0062/Solution1.h<gh_stars>10-100
//
// Created by ooooo on 2020/2/13.
//
#ifndef CPP_0062__SOLUTION1_H_
#define CPP_0062__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* dp[i][j] = dp[i][j-1] + dp[i-1][j]
*/
class Solution {
public:
// n 行 m 列
int uniquePaths(int m, int n) {
if (m == 0 || n == 0) return 0;
vector<vector<int>> dp(n, vector<int>(m, 1));
for (int i = 1; i < n; ++i) {
for (int j = 1; j < m; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[n - 1][m - 1];
}
};
#endif //CPP_0062__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0523-Continuous Subarray Sum/cpp_0523/Solution1.h | //
// Created by ooooo on 6/2/2021.
//
#ifndef CPP_0523_SOLUTION1_H
#define CPP_0523_SOLUTION1_H
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
bool checkSubarraySum(vector<int> &nums, int k) {
int n = nums.size();
if (n < 2) return false;
int preSum = nums[0];
unordered_set<int> s;
s.insert(0);
for (int i = 1; i < n; i++) {
preSum += nums[i];
if (s.count(preSum % k)) {
return true;
}
s.insert((preSum - nums[i]) % k);
}
return false;
}
}
#endif//CPP_0523_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0438-Find-All-Anagrams-in-a-String/cpp_0438/Solution1.h | <reponame>ooooo-youwillsee/leetcode<filename>0438-Find-All-Anagrams-in-a-String/cpp_0438/Solution1.h
//
// Created by ooooo on 2020/3/1.
//
#ifndef CPP_0438__SOLUTION1_H_
#define CPP_0438__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/**
* timeout
*/
class Solution {
public:
bool is_valid(string &s, int begin, int end, unordered_map<char, int> p_map) {
while (begin <= end) {
char c = s[begin];
if (p_map[c]) {
--p_map[c];
} else {
return false;
}
++begin;
}
return true;
}
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> p_map;
for (auto &c: p) ++p_map[c];
int n = p.size();
vector<int> ans;
for (int i = 0, len = s.size(); i <= len - n; ++i) {
if (is_valid(s, i, i + n - 1, p_map)) ans.push_back(i);
}
return ans;
}
};
#endif //CPP_0438__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0589-N-ary-Tree-Preorder-Traversal/cpp_0589/Solution1.h | //
// Created by ooooo on 2020/1/3.
//
#ifndef CPP_0589_SOLUTION1_H
#define CPP_0589_SOLUTION1_H
#include "Node.h"
/**
* recursion
*/
class Solution {
public:
void help(Node *node, vector<int> &vec) {
if (!node) return;
vec.push_back(node->val);
for (auto child: node->children) {
help(child, vec);
}
}
vector<int> preorder(Node *root) {
vector<int> vec;
help(root, vec);
return vec;
}
};
#endif //CPP_0589_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0402-Remove K Digits/cpp_0402/Solution1.h | /**
* @author ooooo
* @date 2020/11/15 09:51
*/
#ifndef CPP_0402__SOLUTION1_H_
#define CPP_0402__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string removeKdigits(string num, int k) {
if (k == num.size()) return "0";
vector<char> vec;
for (int i = 0; i < num.size(); ++i) {
while (!vec.empty() && vec.back() > num[i] && k) {
vec.pop_back();
k--;
}
vec.push_back(num[i]);
}
// 都是递增的,删除最后面的元素
while (k) {
vec.pop_back();
k--;
}
string ans = "";
bool prevHasNum = false;
for (int i = 0; i < vec.size(); ++i) {
if (vec[i] == '0' && !prevHasNum) {
continue;
}
ans.push_back(vec[i]);
prevHasNum = true;
}
return ans == "" ? "0" : ans;
}
};
#endif //CPP_0402__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0173-Binary Search Tree Iterator/cpp_0173/Solution1.h | <gh_stars>10-100
/**
* @author ooooo
* @date 2021/3/28 09:44
*/
#ifndef CPP_0173__SOLUTION1_H_
#define CPP_0173__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class BSTIterator {
public:
stack<TreeNode *> s;
BSTIterator(TreeNode *root) {
if (!root) {
return;
}
TreeNode *cur = root;
while (cur) {
s.push(cur);
cur = cur->left;
}
}
int next() {
TreeNode *node = s.top();
s.pop();
TreeNode *cur = node->right;
while (cur) {
s.push(cur);
cur = cur->left;
}
return node->val;
}
bool hasNext() {
return !s.empty();
}
};
#endif //CPP_0173__SOLUTION1_H_
|
ooooo-youwillsee/leetcode | 0242-Valid-Anagram/cpp_0242/Solution1.h | <filename>0242-Valid-Anagram/cpp_0242/Solution1.h
//
// Created by ooooo on 2019/11/1.
//
#ifndef CPP_0242_SOLUTION1_H
#define CPP_0242_SOLUTION1_H
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
#endif //CPP_0242_SOLUTION1_H
|
ooooo-youwillsee/leetcode | 0216-Combination-Sum-III/cpp_0216/Solution1.h | /**
* @author ooooo
* @date 2020/9/11 11:27
*/
#ifndef CPP_0216__SOLUTION1_H_
#define CPP_0216__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> ans;
void dfs(vector<int> &vec, int i, int k, int n) {
if (vec.size() == k) {
if (n == 0)
ans.push_back(vec);
return;
}
while (i <= 9) {
if (n < i) return;
vec.push_back(i);
dfs(vec, i + 1, k, n - i);
vec.pop_back();
i++;
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> vec;
dfs(vec, 1, k, n);
return ans;
}
};
#endif //CPP_0216__SOLUTION1_H_
|